我也碰到了这道题,我自己写的代码,不能保证解决问题,但是可以参考一下
package com.itheima_1_10;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
/**
* 有五个学生,每个学生有3门课(语文、数学、英语)的成绩,写一个程序接收从键盘输入学生的信息,
输入格式为:name,30,30,30(姓名,三门课成绩),
然后把输入的学生信息按总分从高到低的顺序写入到一个名称"stu.txt"文件中。
要求:stu.txt文件的格式要比较直观,打开这个文件,就可以很清楚的看到学生的信息。
*/
public class Test04 {
public static void main(String[] args) throws Exception {
TreeSet<Student> t = new TreeSet<Student>(new Comparator<Student>(){
@Override
public int compare(Student s1, Student s2) {
// TODO Auto-generated method stub
int num = s1.getToal() - s2.getToal();
int num2 = (num == 0) ? s1.getName().compareTo(s2.getName()) : num ;
return num2;
}
});
Scanner sc = new Scanner(System.in);
for(int x = 0 ; x < 5 ; x++){
System.out.println("请您输入学生姓名");
String name = sc.nextLine();
System.out.println("请您输入学生的语文成绩");
String c = sc.nextLine();
int chinaeseScore = Integer.parseInt(c);
System.out.println("请您输入学生的数学成绩");
String m = sc.nextLine();
int mathScore = Integer.parseInt(m);
System.out.println("请您输入学生的英语成绩");
String e = sc.nextLine();
int englishScore = Integer.parseInt(e);
t.add(new Student(name , chinaeseScore , mathScore , englishScore));
}
BufferedWriter bw = new BufferedWriter(new FileWriter("stu.txt"));
bw.write("姓名 \t\t总分\t\t语文\t\t数学\t\t英语");
bw.newLine();
bw.flush();
for(Student s : t){
bw.write(s.getName() + "\t\t" + s.getToal() + "\t\t" +s.getChinaeseScore() + "\t\t" + s.getMathScore() + "\t\t" + s.getEnglishScore());
bw.newLine();
bw.flush();
}
bw.close();
}
}
class Student {
private String name ;
private int chinaeseScore ;
private int mathScore ;
private int englishScore ;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int chinaeseScore, int mathScore,
int englishScore) {
super();
this.name = name;
this.chinaeseScore = chinaeseScore;
this.mathScore = mathScore;
this.englishScore = englishScore;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinaeseScore() {
return chinaeseScore;
}
public void setChinaeseScore(int chinaeseScore) {
this.chinaeseScore = chinaeseScore;
}
public int getMathScore() {
return mathScore;
}
public void setMathScore(int mathScore) {
this.mathScore = mathScore;
}
public int getEnglishScore() {
return englishScore;
}
public void setEnglishScore(int englishScore) {
this.englishScore = englishScore;
}
public int getToal(){
return chinaeseScore + mathScore + englishScore ;
}
@Override
public String toString() {
return "Student [name=" + name + ", chinaeseScore=" + chinaeseScore
+ ", mathScore=" + mathScore + ", englishScore=" + englishScore
+ "]";
}
}
|