/*有五个学生,每个学生有3门课(语文、数学、英语)的成绩,写一个程序接收
从键盘输入学生的信息,输入格式为:name,30,30,30(姓名,三门课成绩),然后
把输入的学生信息按总分从高到低的顺序写入到一个名称"stu.txt"文件中。要求:stu.txt文件的格式要比较直观,
打开这个文件,就可以很清楚的看到学生的信息。*/
/**思路:
* 1.通过键盘录入一行数据,并将该行中的数据封装成学生对象
* 2.因为有很多个学生,那么就需要存储,使用到集合,因为需要排序,所以用到TreeSet
* 3.将集合写入到一个文件中
* @author Administrator
*
*/
public class Test4{
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Comparator<Student> cmp = Collections.reverseOrder();
Set<Student> stus = StudentInfoTool.getStudents(cmp);
//Set<Student> stus = StudentInfoTool.getStudents();
StudentInfoTool.write2File(stus);
}
}
//用学生类来封装学生的信息
class Student implements Comparable<Student>{
private String name;
private int chinese,math,english;
private int sum;
public Student(String name, int chinese, int math, int english) {
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
sum = chinese+math+english;
}
public int getSum() {
return sum;
}
public String getName() {
return name;
}
//实现接口中的方法,分数相同在比较姓名。如果总分和姓名相同,就是同一个人
@Override
public int compareTo(Student s) {
int num = new Integer(this.sum).compareTo(new Integer(s.sum));
if(num==0)
return this.name.compareTo(s.name);
return num;
}
@Override
public int hashCode() {
return name.hashCode()+sum*60;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配");
Student s = (Student) obj;
return this.name.equals(s.name)&&this.sum==s.sum;
}
@Override
public String toString() {
return "student["+name+","+chinese+","+math+","+english+","+sum+"]";
}
}
//从键盘上读入的学生信息存入到集合中
class StudentInfoTool{
public static Set<Student> getStudents() throws IOException{
return getStudents(null);
}
public static Set<Student> getStudents(Comparator<Student> cmp) throws IOException{
//定义一个字符缓冲流用于读取键盘中输入的信息
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Set<Student> stus = null;
if(cmp==null)
stus = new TreeSet<Student>();
else
stus = new TreeSet<Student>(cmp);
String line = null;
while((line=br.readLine())!=null){
if("over".equals(line))
break;
String[] info = line.split(",");
Student stu = new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),
Integer.parseInt(info[3]));
stus.add(stu);
}
return stus;
}
//将集合写入到一个文件中
public static void write2File(Set<Student> stus) throws IOException{
//定义一个字符流用于将集合中的信息写入到文件中
BufferedWriter bw = new BufferedWriter(new FileWriter("d:/stu.txt"));
for(Student stu : stus){
bw.write(stu.toString());
//bw.write(stu.getSum()+"");
bw.newLine();
bw.flush();
}
bw.close();
}
}
|
|