1、求 2~200 之间的所有素数,将求得的结果保存到 PRIME.TXT 文件中。
import java.io.PrintStream;
/**
* 求 2~200 之间的所有素数,将求得的结果保存到 PRIME.TXT 文件中
*/
public class Main {
public static void main(String[] args) throws Exception { //所有异常抛出
PrintStream file = new PrintStream("PRIME.TXT");
for (int i = 2; i <= 200; i++) {
if (isPrime(i)) {
file.println(i);
}
}
file.close();
}
public static boolean isPrime(int n) { // 判断 n 是否为素数
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
}
2、输入 5 个学生的信息(包含学号、姓名、3 科成绩),统计各学生的总分,然后将学生信息和统计结果存入二进制数据文件 STUDENT.DAT 中。
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
Student[] students = {new Student("001", "张三", 89, 90, 91),
new Student("002", "李四", 92, 93, 94),
new Student("003", "王五", 95, 96, 97),
new Student("004", "赵六", 98, 99, 100),
new Student("005", "田七", 100, 100, 100)};
ser(students);
}
public static void ser(Object obj[]) throws Exception {
File file = new File("d:\\STUDENT.DAT");
ObjectOutputStream oos = null;
OutputStream out = new FileOutputStream(file);
oos = new ObjectOutputStream(out);
oos.writeObject(obj);
oos.close();
}
}
class Student implements Serializable {
private String id;
private String name;
private int chinese;
private int math;
private int english;
public Student() {
}
public Student(String id, String name, int chinese, int math, int english) {
this.id = id;
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
}
3、从第 2 题中建立的 STUDENT.DAT 文件中读取数据,寻找平均分最高的学生,并输出该学生的所有信息。
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
Object[] obj = dser();
Student stuMax = (Student) obj[0];
for (int i = 0; i < obj.length; i++) {
Student student = (Student) obj[i];
if ((student.getEnglish()+student.getMath()+student.getEnglish())/3.0> (stuMax.getChinese()+stuMax.getMath()+stuMax.getEnglish())/3.0) {
stuMax = student;
}
}
System.out.println("学号:"+stuMax.getId()+" 姓名:"+stuMax.getName() + " 语文成绩:" + stuMax.getChinese() + " 数学成绩:" + stuMax.getMath() + " 英语成绩:" + stuMax.getEnglish());
}
public static Object[] dser() throws Exception {
File file = new File("d:\\STUDENT.DAT");
ObjectInputStream ois = null;
InputStream input = new FileInputStream(file);
ois = new ObjectInputStream(input);
Object[] obj = (Object[]) ois.readObject();
ois.close();
return obj;
}
}