用比较器
Scanner sc = new Scanner(System.in);
System.out.println("dadjhasjhdai");
TreeSet<student29> ts = new TreeSet<>( new Comparator<student29>() {
@Override
public int compare(student29 o1, student29 o2) {
int num = o1.getSum()-o2.getSum();
return num==0?1:num;
}
});
//BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("xxx.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("scorse1.txt"));
while(ts.size()<5){
String s = sc.nextLine();
String [] arr = s.split(",");
for (int i = 0; i < arr.length; i++) {
int chinses = Integer.parseInt(arr[1]);
int math = Integer.parseInt(arr[2]);
int english = Integer.parseInt(arr[3]);
ts.add(new student29(arr[0],chinses,math,english));
}
for (student29 stu : ts) {
bw.write(stu.toString());
}
}
实习comparable
public class demo04 {
public static void main(String[] args) throws Exception {
TreeSet<Student> ts = getSet();
writeToFile(ts);
}
//将集合数据写入到文件,接收一个集合
public static void writeToFile(TreeSet<Student> ts) throws Exception {
BufferedWriter bufw = new BufferedWriter(new FileWriter("stu.txt"));
for (Student student : ts) {
//System.out.println(student.toString());
bufw.write(student.toString());
bufw.newLine();
bufw.flush();
}
bufw.close();
}
//从键盘输入信息,将信息包装成对象,将对象存储到集合中,返回一个集合
public static TreeSet<Student> getSet(){
TreeSet<Student> ts = new TreeSet<Student>();
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String str = sc.nextLine();
if(str.equals("over")){
sc.close();
break;
}
String[] s = str.split(",");
ts.add(new Student(s[0],Integer.parseInt(s[1]),Integer.parseInt(s[2]),Integer.parseInt(s[3])));
}
return ts;
}
}
class Student implements Comparable<Student>{
private String name;
private int ch,math,en;
private int sum;
public Student(String name,int ch,int math,int en) {
this.name = name;
this.ch = ch;
this.math = math;
this.en = en;
this.sum = ch+math+en;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCh() {
return ch;
}
public void setCh(int ch) {
this.ch = ch;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEn() {
return en;
}
public void setEn(int en) {
this.en = en;
}
public int getSum() {
return sum;
}
@Override
public int compareTo(Student s) {
if(!(s instanceof Student))
throw new RuntimeException("类型错误");
int num = new Integer(this.sum).compareTo(new Integer(s.sum));
if(num==0){
return this.name.compareTo(s.name);
}
return num;
}
@Override
public int hashCode() {
return name.hashCode()+sum*66;
}
@Override
public boolean equals(Object obj) {
Student s = (Student)obj;
return this.name.equals(s.name) && this.ch==s.ch && this.math==s.math && this.en==s.en;
}
@Override
public String toString() {
return "姓名:"+name+" 语文:"+ch+" 数学:"+math+" 英语:"+en+" 总分"+sum;
}
} |