![d38d7aeec9f3afdf25a225499aa36d55.png](https://img-blog.csdnimg.cn/img_convert/d38d7aeec9f3afdf25a225499aa36d55.png)
题目:由控制台按照固定格式输入学生信息,包括学号,姓名,年龄信息,当输入的内容为exit退出;将输入的学生信息分别封装到一个Student对象中,再将每个Student对象加入到一个集合中,要求集合中的元素按照年龄大小正序排序;最后遍历集合,将集合中学生信息写入到记事本,每个学生数据占单独一行。
源代码:
public class Student implements Comparable<Student>{
private Integer num;
private String name;
private Integer age;
//省略getter和setter方法
//省略构造方法
public int compareTo(Student stu) {
return this.age-stu.age;
}
public String toString() {
return "Student [age=" + age + ", name=" + name +
", num=" + num + "]";
}
}
public class Test {
public static void main(String[] args) {
Set<Student> stuSet = saveStudentInfo();
outputInfo(stuSet);
}
private static Set<Student> saveStudentInfo() {
Scanner input = new Scanner(System.in);
// 保存学生信息的TreeSet集合对象
Set<Student> stuSet = new TreeSet<Student>();
while (true) {
// 输入提示
System.out.println("请输入学生信息:(学号#姓名#年龄)");
String inputData = input.nextLine();
// 判断是否退出 inputData.equals("exit")
if ("exit".equals(inputData)) {
break;
}
// 将用户输入的学生信息分割为String[]
String[] info = inputData.split("#");
// 将输入信息封装到Student对象中
Student stu = new Student(Integer.parseInt(info[0]), info[1],Integer.parseInt(info[2]));
// 将学生对象加入集合
stuSet.add(stu);
}
return stuSet;
}
private static void outputInfo(Set<Student> stuSet) {
File file = new File("e:/student.txt");
// 创建文件输出流对象
FileWriter fw = null;
try {
fw = new FileWriter(file);
Iterator<Student> it = stuSet.iterator();
while (it.hasNext()) {
String info = it.next().toString();
// 将info字符串,写入记事本
fw.write(info);
// 完成换行功能
fw.write("rn");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
效果如下:
请输入学生信息:(学号#姓名#年龄)
132#张三#20
请输入学生信息:(学号#姓名#年龄)
123#李四#21
请输入学生信息:(学号#姓名#年龄)
124#王五#19
请输入学生信息:(学号#姓名#年龄)
exit