需求:
1.有5个学生,每个学生有三门功课
2.从键盘输入以上数据(姓名,三门课成绩)
3.输入格式为:zhangshan,30,40,60并计算出总成绩
4.把学生信息和计算出来的总成绩按从低到高的顺序进行存储
思路:
1.先创建一个学生对象,实现比较器,让学生对象自身具备比较性,同时要复写hashcode()和equeas()方法
2.创建键盘录入,同时创建TreeSet集合,将键盘录入的数据存入集合
3.将集合中的数据存入到文件中
import java.io.*;
import java.util.*;
class StudentInfoTest
{
public static void main(String[] args) throws IOException
{
//自定义比较器
Comparator<Student> cmp=Collections.reverseOrder();
Set<Student> treeset=StudentInfoTool.getStudentInfo(cmp);
StudentInfoTool.writeToFile(treeset);
}
}
//创建学生对象
class Student implements Comparable<Student>
{
private String name;
private int cn;
private int ma;
private int en;
private int sum;
Student(String name,int cn,int ma,int en)
{
this.name=name;
this.cn=cn;
this.ma=ma;
this.en=en;
sum=cn+ma+en;
}
public String getName()
{
return name;
}
public int getSum()
{
return sum;
}
//复写hashCode方法
public int hashCode()
{
return this.name.hashCode()+sum*6;
}
//复写equals方法
public boolean equals(Object obj)
{
if(obj instanceof Student)
throw new ClassCastException("类型不匹配!");
Student str=(Student)obj;
return this.name.equals(str.getName()) && this.sum==str.getSum();
}
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 toString()
{
return "["+name+", "+cn+", "+ma+", "+en+"]";
}
}
//创建操作学生的工具类
class StudentInfoTool
{
//空比较器
public static Set<Student> getStudentInfo() throws IOException
{
return StudentInfoTool.getStudentInfo(null);
}
public static Set<Student> getStudentInfo(Comparator<Student> cmp) throws IOException
{
//键盘录入
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
//创建TreeSet集合,cmp为自定义比较器
Set<Student> treeset=new TreeSet<Student>(cmp);
String line=null;
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]));
treeset.add(stu);
}
bufr.close();
System.out.println(treeset);
return treeset;
}
//存入文件方法
public static void writeToFile(Set<Student> stu) throws IOException
{
//文件写入流
BufferedWriter bufw=new BufferedWriter(new FileWriter("studentInfo.txt"));
//从集合里取出学生信息
for(Student s : stu)
{
bufw.write(s.toString()+"\t");
bufw.write(s.getSum()+"");
bufw.newLine();
bufw.flush();
}
bufw.close();
}
}