JAVA编程:输入5个学生的信息(包含学号、姓名、3科成绩),统计

各学生的总分,然后将学生信息和统计结果存入二进制数据文件STUDENT.DAT中。

能直接运行的:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.io.*;

import javax.naming.BinaryRefAddr;
public class Student implements Serializable{//Serializable是申明这个类可以被序列化

/**
* @param args
*/
public static void main(String[] args) {
ArrayList <Student> ss=new ArrayList<Student>();

for(int i=0;i<5;i++)//初始化5个学生
{
Student s=new Student(i,"学生"+i);
s.chenese_score=i+50;
s.english_score=i+75;
s.math_score=i+80;
ss.add(s);
}

try {
FileOutputStream fos=new FileOutputStream("d:/STUDENT.DAT");
try {
ObjectOutputStream oos=new ObjectOutputStream(fos);

for(int i=0;i<ss.size();i++)//初始化5个学生
{
Student s=ss.get(i);
oos.writeObject(s);//将学生遍历出来写入文件中

}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//从文件中读取一个学生出来出来
try {
FileInputStream fis=new FileInputStream("d:/STUDENT.DAT");
try {
ObjectInputStream ois=new ObjectInputStream(fis);
try {

Student s=(Student)ois.readObject();
System.out.println("学生名为 "+s.name+"的总分为:"+s.getAll_score());

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public int id;
public String name;
public int chenese_score;
public int math_score;
public int english_score;
public int all_score;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getAll_score()//获取总成绩
{
return this.chenese_score+this.english_score+this.math_score;
}

}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-06-03
貌似序列化存储后的文件就是二进制文件,不大确定,你试试,建立二个类 一个学生信息类 另外一个用来存储的类 都声明可序列化 即implements Serializable 另外要求类所有属性都用标准的get set方法 好像还需要不需要参数的构建方法 获得输入信息后用ObjectInputStream存储读取就可以了
第2个回答  2010-06-03
输入统计是很基础的东西了,稍微看看书和例子就能做出来了。
写数据对象到文件最好用DataOutputStream。
第3个回答  2010-06-03
这叫问题吗?这种问题是不会有人回答的。我是来好心告诉你不用等了。
拿两分走人。
相似回答