• 向指定的txt文件中写入键盘输入的内容,然后再重新读取该文件的内容,显示到控制台上。
• 键盘录入5个学生信息(姓名, 成绩),按照成绩从高到低存入文本文件。
package 复习第七章作业第四答题;
import java.io.*;
import java.util.*;
public class Demo {
public static void main(String[] args)throws IOException {
TreeSet<Student> ts=new TreeSet<Student>();
Scanner sc1=new Scanner(System.in);
Scanner sc2=new Scanner(System.in);
int num;
String name;
int score;
System.out.println("请输入要录入学生的人数:");
num=sc1.nextInt();
for(int i=1;i<=num;i++) {
System.out.println("请输入第"+i+"个学生的信息");
System.out.print("姓名:");
name = sc2.nextLine();
System.out.print("分数:");
score = sc1.nextInt();
Student s=new Student(name,score);
ts.add(s);
}
FileWriter writer = new FileWriter("C:\\Users\\无意\\Desktop\\Student2.txt");
BufferedWriter bw = new BufferedWriter(writer);
bw.write("学生信息如下:");
bw.newLine();
bw.write("姓名 成绩");
bw.newLine();
bw.flush();
for(Student s:ts) {
StringBuilder sb = new StringBuilder();
sb.append(s.getName()).append(" ").append(s.getScore());
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
}
}
class Student implements Comparable<Student>{
private String name;
private int score;
public Student(String name,int score) {
this.name=name;
this.score=score;
}
public String getName() {
return name;
}
public void SetName(String name) {
this.name=name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score=score;
}
@Override
public int compareTo(Student o) {
int i = this.score-o.score;
return i==0 ? o.getName().compareTo(this.getName()) : i;
}
}