【需求】:
有五个学生,每个学生有三门课的成绩
从键盘输入以上数据(包括姓名,三门课的成绩)
输入的格式如:zhangsan,30,40,50 计算出总成绩
并把学会的信息和计算出的总分数高低顺序存放在磁盘文件"student.txt"
【代码】:
import java.io.*;
import java.util.*;
class Student implements Comparable<Student>
{
private String name;
private double chinese;
private double math;
private double english;
private double sum;
public double getSum(){
return this.sum;
}
Student(String name,double chinese,double math,double english){
this.name=name;
this.chinese=chinese;
this.math=math;
this.english=english;
sum=chinese+math+english;
}
//重写hashCode()方法
public int hashCode(){
return name.hashCode();
}
//重写equals()方法
public boolean equals(Object o){
if(!(o instanceof Student)){
throw new RuntimeException("不是学生类对象");
}
Student s=(Student)o;
return this.name.equals(s.name)&&this.sum==s.sum;
}
public int compareTo(Student s){
int num=new Double(this.sum).compareTo(new Double(s.sum));
if(num==0){
return this.name.compareTo(s.name);
}
return num;
}
public String toString(){
return name+","+chinese+","+math+","+english;
}
}
class StudentInforTool
{
public static Set<Student> getStudents()throws IOException{
return getStudents(null);
}
public static Set<Student> getStudents(Comparator<Student> comp) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String line=null;
Set<Student> stus=new TreeSet<Student>();
if(comp==null){
stus=new TreeSet<Student>();
}else{
stus=new TreeSet<Student>(comp);
}
while((line=br.readLine())!=null){
if("over".equals(line))
break;
String[] info=line.split(",");
Student stu=new Student(info[0],Double.parseDouble(info[1]),
Double.parseDouble(info[2]),Double.parseDouble(info[3]));
stus.add(stu);
}
return stus;
}
public static void writeStudents(Set<Student> stus)throws IOException{
BufferedWriter bw=new BufferedWriter(new FileWriter("student.txt"));
for(Student stu:stus){
bw.write(stu.toString()+"\t\t");
bw.write(stu.getSum()+"");
bw.newLine();
bw.flush();
}
bw.close();
}
}
class StuScore
{
public static void main(String[] args) throws IOException
{
Comparator<Student> comp=Collections.reverseOrder();
Set<Student> stus=StudentInforTool.getStudents(comp);
StudentInforTool.writeStudents(stus);
}
}
【输出截图】:
键盘录入:
文件输出: