看了一下你的程序,出现问题的地方很多,对于集合的内容好像还没有掌握。import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Set;
import java.util.TreeSet;
/*
* 程序的需求是:从命令行输入学生的名字,数学语文英语成绩,
* 格式为zhangsan,89,78,78
* 根据总分对学生进行排名
如果总分不同 按总分排名
如果总分相同 姓名不同则按哈希码值对名字进行排序
并在输出文件中输出结果
*/
public class StudentSortDemo {
/**
* @param args
*/
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
Set<Students> set = new TreeSet<Students>();
while ((line = br.readLine()) != null) {
if ("over".equals(line))
break;
String[] stuinfo = line.split(",");
Students s = new Students(stuinfo[0],
Integer.parseInt(stuinfo[1]),
Integer.parseInt(stuinfo[2]),
Integer.parseInt(stuinfo[3]));
set.add(s);
}
PrintWriter pw = new PrintWriter(System.out,true);//定义一个打印流,将输出打印到控制台
for(Students s : set){
pw.println(s.toString());
//pw.println(s.getSum());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br !=null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* 定义一个学生类,实现Comparable接口,使其就有比较性
* 要比较,就要实现equals方法和hashcode方法。
*/
class Students implements Comparable<Students> {
private String name;
private int chinese;
private int math;
private int english;
private int sum;
public Students(String name, int chinese, int math, int english) {
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
this.sum = chinese + math + english;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinese() {
return chinese;
}
public void setChanese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
public int hashCode() {
return this.name.hashCode() + this.sum % 2*7;
}
public boolean equals(Object obj) {
if (obj instanceof Students)
throw new RuntimeException("类型匹配");
Students stu = (Students) obj;
return this.name.equals(stu.name);
}
public String toString() {
return name + "[" + chinese + "," + math + "," + english + "]"
+ " " + sum;
}
/*
* 复写比较方法,如果学生的总成绩相等,则按学生姓名的自然循序排序
*/
public int compareTo(Students o) {
int num = new Integer(this.sum).compareTo(new Integer(o.sum));
if (num == 0)
return this.name.compareTo(o.name);
return num;
}
}给一个我刚写的程序。你可以对照的看下 |
|