/*
有五个学生,每个学生有3门课的成绩,
从键盘输入以上数据(包括姓名,三门课成绩)
输入的格式:如zhangsan,30,40,50,计算出总成绩
并把学生的信息和计算出的总分数高低顺序存放在磁盘文件“stuinfo.txt”中。
1.描述学生对象。
2.定义一个可操作学生对象的工具类。
思想:
1.通过获取键盘录入一行数据,并将该数据中的信息取出,封装成学生对象。
2.因为学生有很多,那么就需要存储,使用到集合。因为要对学生的总分排序,
所以可以使用TreeSet
3.将集合的信息写入到一个文件中。
*/
import java.io.*;
import java.util.*;
class Student implements Comparable<Student>
{
private String name;
private int cn,math,en;
private int sum;
Student(String name,int cn,int math,int en)
{
this.name=name;
this.cn=cn;
this.math=math;
this.en=en;
sum=cn+math+en;
}
public int hashCode()
{
return name.hashCode()+sum;
}
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;
}
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 "student["+name+","+cn+","+math+","+en+"]";
}
}
class StudentTool
{
//键盘录入信息存入TreeSet集合,并排序了
public static TreeSet<Student> getStudent()throws IOException
{
BufferedReader bufw = new BufferedReader(new InputStreamReader(System.in));
TreeSet<Student> ts = new TreeSet<Student>(Collections.reverseOrder());//强行逆转比较器:不带参数时,逆转默认比较器
// 带参数时,逆转指定比较器
String line=null;
while((line=bufw.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]));
ts.add(stu);
}
bufw.close();
return ts;
}
//集合中的信息写入文件
public static void writeToFile(TreeSet<Student> ts)throws IOException
{
BufferedWriter bufw = new BufferedWriter(new FileWriter("stuinfo.txt"));
for(Student s : ts)
{
bufw.write(s.toString());
bufw.newLine();
bufw.flush();
}
bufw.close();
}
}
class StudentInfoTest
{
public static void main(String[] args) throws Exception
{
TreeSet<Student> ts = StudentTool.getStudent();
StudentTool.writeToFile(ts);
}
}
day21/StudentInfoTest.java
最新推荐文章于 2018-07-21 09:56:00 发布