import java.util.TreeSet;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Comparator;
class ScannerStudent
{
public static void main(String[] args)
{
//创建集合,创建Comparator内部类子类对象并实现方法
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>(){
public int compare(Student s1, Student s2){
int num = s2.getAge() - s1.getAge();
num = (num == 0)?(s1.getName().compareTo(s2.getName())):num;
return num;
}
});
//采用循环,多次录入
while(true){
Scanner sc = new Scanner(System.in);
System.out.println("请输入学生姓名:");
String name = sc.nextLine();
//定义录入结束的标记
if(name.equals("over")){
break;
}
System.out.println("请输入学生年龄:");
int age = sc.nextInt();
//将对象存入集合
ts.add(new Student(name,age));
}
for(Student s : ts){
System.out.println(s.getName() + "..." + s.getAge());
}
//将对象写入文件
//创建高效字符流对象
BufferedWriter bw = null;
try{
bw = new BufferedWriter(new FileWriter("E:\\uknow.txt"));
for(Student s : ts){
String name = s.getName();
int age = s.getAge();
bw.write(name + "=" + age);
bw.newLine();
bw.flush();
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(bw != null){
try{
bw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
class Student{
private String name;
private int age;
public Student(){
super();
}
public Student(String name, int age){
this.name = name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
}
|
|