import java.io.FileWriter
import java.io.IOException
public class PrimeNumberFinder {
public static void main(String[] args) {
// 设置范围
int start = 20000000
int end = 300000000
// 用于写入文件的 BufferedWriter
BufferedWriter writer = null
try {
// 初始化 BufferedWriter
writer = new BufferedWriter(new FileWriter("primefile.dat"))
// 遍历范围内的所有数字
for (int i = starti <= endi++) {
// 如果这个数字是素数,写入文件
if (isPrime(i)) {
writer.write(String.valueOf(i))
writer.newLine()
}
}
} catch (IOException e) {
// 如果出现 IOException,输出错误信息
e.printStackTrace()
} finally {
// 最后关闭 BufferedWriter
if (writer != null) {
try {
writer.close()
} catch (IOException e) {
e.printStackTrace()
}
}
}
}
// 判断一个数字是否为素数
public static boolean isPrime(int n) {
// 对于小于 2 的数字,直接返回 false
if (n <2) {
return false
}
// 从 2 开始遍历到 n-1,如果能被 n 整除,则返回 false
for (int i = 2i <ni++) {
if (n % i == 0) {
return false
}
}
// 如果执行到这里,说明没有小于 n 的数字能被 n 整除,返回 true
return true
}
实现代码如下:
Student类:
public class Student {
private String name
private String sex
private int age
private double chinese
private double math
private double english
public String getName() {
return name
}
public void setName(String name) {
this.name = name
}
public String getSex() {
return sex
}
public void setSex(String sex) {
this.sex = sex
}
public int getAge() {
return age
}
public void setAge(int age) {
this.age = age
}
public double getChinese() {
return chinese
}
public void setChinese(double chinese) {
this.chinese = chinese
}
public double getMath() {
return math
}
public void setMath(double math) {
this.math = math
}
public double getEnglish() {
return english
}
public void setEnglish(double english) {
this.english = english
}
}
-----------------------------------------------------------------
StudentTest类:(测试类)
import java.util.Scanner
public class StudentTest {
public static void main(String[] args) {
Student student = new Student()
Scanner sc = new Scanner(System.in)
System.out.println("请输入姓名:")
student.setName(sc.next())
System.out.println("请输入性别:")
student.setSex(sc.next())
System.out.println("请输入年龄:")
student.setAge(sc.nextInt())
System.out.println("请输入语文成绩、数学成绩、英语成绩:")
student.setChinese(sc.nextDouble())
student.setMath(sc.nextDouble())
student.setEnglish(sc.nextDouble())
Double count = student.getChinese()+ student.getMath()+student.getEnglish()
System.out.println("姓名:"+student.getName()+" 性别:"+student.getSex()+" 年龄:"+student.getAge())
System.out.println("总分:"+count+" 平均分:"+count/3)
}
}
运行结果为:
下面是用Java编写的程序,可以实现输出1到100之间的所有素数:Copy codepublic class Main {
public static void main(String[] args) {
for (int i = 2i <= 100i++) {
// 判断i是否为素数
boolean isPrime = true
for (int j = 2j <ij++) {
if (i % j == 0) {
// i被j整除,说明i不是素数
isPrime = false
break
}
}
if (isPrime) {
// i是素数,输出i
System.out.println(i)
}
}
}
}
这个程序使用了两层循环,外层循环从2开始遍历1到100之间的数字,内层循环用来判断当前数字是否为素数。如果是素数,就输出这个数字。
希望这个程序能帮到你。