/*
练习:将学生姓名和语数外三门课的分数录入,然后将三门分数加和,按照总分由高到低及
姓名默认排序的顺序存储到studentinfo.txt文件中。
思路:1.描述学生类
2.通过键盘获取学生的数据,并将该行中的数据取出封装为学生对象
3.定义一个可操作学生对象的工具类
4.要将多个学生的信息存储起来且要排序,所以选用TreeSet集合
5.将集合中的信息写入到文件中
*/
package io;
import java.util.*;
import java.io.*;
//新建一个学生类
class Student implements Comparable<Student> //使得学生类具备比较性
{
private String name;
private int CN;
private int MA;
private int EN;
private int sum;
//构造函数要求内容为String name, int CN, int MA, int EN
Student(String name, int CN, int MA, int EN)
{
this.name = name;
this.CN = CN;
this.MA = MA;
this.EN = EN;
this.sum = CN+MA+EN;
}
//继承Comparable接口必须覆盖compareTo方法,其内部比较用compareTo方法,且类内部要覆盖hashCode和equals两个方法,
//为默认比较提供功能,注意此处整数的比较要建立基本数据类型对象包装类,equals方法中的比较与此不同,详见下
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;
}
public String getName()
{
return name;
}
public int getSum()
{
return sum;
}
public int hashCode()
{
return name.hashCode()+sum*53;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("类型不一致");
Student s = (Student)obj;
//equals中字符串的比较用equals方法,数字的比较用==
return this.name.equals(s.name) && this.sum==s.sum;
}
public String toString()
{
return name+":语文="+CN+";数学="+MA+";英语="+EN;
}
}
class StudentInfoTool
{
//注意:集合上要加泛型
public static TreeSet<Student> getStudents() throws IOException
{
return getStudents(null);
}
public static TreeSet<Student> getStudents(Comparator<Student> cmp) throws IOException
{
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); //建立一个读取流缓冲区
String line = null;
TreeSet<Student> stus = null;
if (cmp==null)
stus = new TreeSet<Student>(); //建立一个TreeSet集合
else
stus = new TreeSet<Student>(cmp);
while ((line=bufr.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);
}
bufr.close();
return stus;
}
public static void writeToFile(TreeSet<Student> stus) throws IOException
{
BufferedWriter bufw = new BufferedWriter(new FileWriter("studentinfo.txt"));
for (Student s : stus)
{
bufw.write(s.toString()+"\t");
bufw.write(s.getSum()+""); //此处,sum即总分原为整数变为字符串后可避免乱码的产生
bufw.newLine();
bufw.flush();
}
bufw.close();
}
}
class StudentInfo
{
public static void main(String[] args) throws IOException
{
Comparator<Student> cmp = Collections.reverseOrder(); //通过Collections类中的reverseOrder方法构造一个反序的比较器
TreeSet<Student> stus = StudentInfoTool.getStudents(cmp); //新建一个Student的TreeSet集合并调用StudentInfoTool中
//的getStudents方法
StudentInfoTool.writeToFile(stus); //调用writeToFile方法将数据输入到指定文件
}
}
|
|