本帖最后由 梁秋瑜 于 2013-5-27 20:43 编辑
public class Student implements Comparable<Student> {
private String name;
private int chinese;
private int math;
private int english;
private int sum;
public Student() {
super();
}
public Student(String name, int chinese, int math, int english) {
super();
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
this.sum = chinese + math + english;
}
@Override
public String toString() {
return name + "," + chinese + "," + math + "," + english + "," + sum;
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
int x = this.sum - o.sum;
return x == 0 ? 1 : 0;
}
}
public class Exersicer5 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
Set<Student> set = new TreeSet<>();
System.out.println("请输入学生的成绩,按格式输入:姓名,chinese的成绩,math的成绩,english的成绩,如:张帅,89,89,87");
while (sc.hasNext()) {
String s = sc.nextLine();
if ("quit".equals(s)) {
sc = new Scanner(new FileInputStream("student.txt"));
continue;
}
String[] arr = s.split(",");
Student st = new Student(arr[0],Integer.parseInt(arr[1]),Integer.parseInt(arr[2]),Integer.parseInt(arr[3]));
set.add(st);
}
System.out.println("输出排序后的成绩:");
BufferedWriter bw = new BufferedWriter (new FileWriter("student.txt"));
for (Student st : set) {
System.out.println(st);
bw.write(st.toString());
bw.newLine();
}
bw.close();
}
}
//编译没什么问题,就是没能得到想要的结果,只能存一个学生的成绩,应该是可以保存学生的成绩并保存的
|
|