本帖最后由 杨增坤 于 2013-10-11 16:30 编辑
需求:想要键盘录入三学生的姓名及成绩,并按成绩总分的升序排列。
我写的代码,运行总是在以下标记行报错,想了一晚上了,还是不知道为啥。
import java.io.*;
import java.util.*;
class xuesheng
{
public static void main(String[] args)throws Exception
{
TreeSet<Student> ts = new TreeSet<Student>();
Student s = new Student();
for(int i=1;i<4;i++) //键盘录入三个学生信息,姓名加三门成绩,并按照成绩排序
{
System.out.println("请输入第" + i + "个学生姓名:");
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
s.setName(bufr.readLine());
System.out.println("请输入第 "+i+"个学生成绩1;");
BufferedReader bufr1 = new BufferedReader(new InputStreamReader(System.in));
s.setStore1(Double.parseDouble(bufr1.readLine()));
System.out.println("请输入第" + i + "个学生成绩2;");
BufferedReader bufr2 = new BufferedReader(new InputStreamReader(System.in));
s.setStore2(Double.parseDouble(bufr2.readLine()));
System.out.println("请输入第" + i + "个学生成绩3;");
BufferedReader bufr3 = new BufferedReader(new InputStreamReader(System.in));
s.setStore3(Double.parseDouble(bufr3.readLine()));
ts.add(s);
//这里总是报错,Exception in thread "main" java.lang.ClassCastException: wo.Student cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at wo.xuesheng.main(xuesheng.java:42)
}
Iterator<Student> it = ts.iterator();
while(it.hasNext())
{
Student s1 = it.next();
System.out.println("姓名:"+s1.getName()+" 三门课成绩: "+s1.getStore1()+" , "+s1.getStore2()+" , "+s1.getStore3()+" 总成绩 "+s1.getSum()+";");
}
}
}
class Student implements Comparator<Object>
{
private String name;
private double store1;
private double store2;
private double store3;
public void setName(String name)
{
this.name = name;
}
public void setStore1(double store1)
{
this.store1 = store1;
}
public void setStore2(double store2)
{
this.store2 = store2;
}public void setStore3(double store3)
{
this.store3 = store3;
}
public double getStore1()
{
double s = store1;
return s;
}public double getStore2()
{
double s = store2;
return s;
}
public double getStore3()
{
double s = store3;
return s;
}
public String getName()
{
return name;
}
public double getSum()
{
double s = store1+store2+store3;
return s;
}
public int compare(Object obj1,Object obj2)
{
if(!( obj1 instanceof Student) & !( obj2 instanceof Student))
{
throw new RuntimeException("duixiangcuowu");
}
Student s1 = (Student)obj1;
Student s2 = (Student)obj2;
int num = new Double(s1.getSum()).compareTo(new Double(s2.getSum()));
if(num == 0)
return s1.getName().compareTo(s2.getName());
return num;
}}
|