public class Testfile {
public static void main(String[] args) throws IOException {
// 定义TreeSet集合实现Comparator这个接口
TreeSet<Studentss> set = new TreeSet<Studentss>(
new Comparator<Studentss>() {
// 重写compare这个方法类实现按成绩排序输出
@Override
public int compare(Studentss o1, Studentss o2) {
return (int) (o1.getChinese()- o2.getChinese());
}
});
// 实例化Student类,带参,
System.out.println("请输入第一个学生的各门成绩");
Studentss st=new Studentss();
Studentss se=getAll(st);
System.out.println("请输入第二个学生的各门成绩");
Studentss st1=new Studentss();
Studentss se1=getAll(st1);
System.out.println("请输入第三个学生的各门成绩");
Studentss st2=new Studentss();
Studentss se2=getAll(st2);
System.out.println("请输入第四个学生的各门成绩");
Studentss st3=new Studentss();
Studentss se3=getAll(st3);
System.out.println("请输入五个学生的各门成绩");
Studentss st4=new Studentss();
Studentss se4=getAll(st4);
// 将Student对象添加到集合中
set.add(se);
set.add(se1);
set.add(se2);
set.add(se3);
set.add(se4);
// 用迭代器编译
Iterator<Studentss> it = set.iterator();
while (it.hasNext()) {
Studentss ss = it.next();
System.out.println(ss.getName()+"语文是:" + ss.getChinese()+ ",英语是:" + ss.getEnglish()
+ "数学是:" + ss.getMath());
String sting=ss.getName()+","+ss.getChinese()+","+ss.getEnglish()+","+ss.getMath();
try {
File file=new File("D:\\snt.txt");
if(!file.exists()){
file.createNewFile();
}
BufferedWriter bu=new BufferedWriter(new FileWriter(file));
bu.write(sting);
bu.newLine();
bu.flush();
bu.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static Studentss getAll(Studentss rt){
Scanner input=new Scanner (System.in);
System.out.println("请输姓名:");
String name=input.next();
System.out.println("请输入语文成绩 分/");
int chinese=input.nextInt();
System.out.println("请输入英语成绩 分/");
int english=input.nextInt();
System.out.println("请输入数学成绩 分/");
int math=input.nextInt();
Studentss s=new Studentss(name,chinese,english, math);
return s;
}
}
// 定义一个Student类
class Studentss {
String name;
int chinese;
int english;
int math;
// 有无参,带参构造
Studentss() {
}
Studentss(String name,int chinese, int english, int math) {
this.name=name;
this.chinese = chinese;
this.english = english;
this.math = math;
}
// 实现get,set方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return chinese+","+english+","+math;
}
}
为什么在程序执行完时。你所建成的File file=new File("D:\\snt.txt");这个文本里面只有最后一个学生的信息啊?我想把五个学生的信息都打印到这个文本里面?高手啊 ??求助 。。
|