帮忙找一下问题所在!
/*
希望在学生毕业的时候统计出学生在校期间考试成绩的排名,
写一个Student类,其中用集合来管理每个学生的各个科目的考试成绩,
将多个Student对象放在集合中,打印出学生的总分以及排名
*/
import java.util.*;
public class SortStudent{
public static void main(String[] args){
List <Student> l=new ArrayList <Student> ();
l.add(new Student( "hlonger ",30));
l.add(new Student( "bluelaster ",19));
l.add(new Student( "mk ",24));
Collections.sort(l);
print(l);
}
public static void print(List <Student> li){
Iterator <Student> it=li.iterator();
for(Student s:li)
System.out.println(s);
}
}
class Student implements Comparable <Student> {
private String name;
private int age;
Random rd=new Random();
public Student(){}
public Student(String name,int age){
this.name=name;
this.age=age;
}
List <Kecheng> li=new ArrayList <Kecheng> ();
li.add(new Course( "英语 ",rd.nextInt(100)));
li.add(new Course( "物理 ",rd.nextInt(100)));
li.add(new Course( "化学 ",rd.nextInt(100)));
li.add(new Course( "语文 ",rd.nextInt(100)));
public String toString(){
return "Student: "+name+ " Age: "+age;
}
public double getSumOfScore(List <Kecheng> li){
double sum=0.0;
for(int i=0;i <li.size();i++)
sum+=li[i].getScore();
return sum;
}
public int compareTo(Student s){
return (int)(this.getSumOfScore(this.li)-s.getSumOfScore(s.li));
}
}
class Kecheng{
private String cname;
private double score;
public Kecheng(){}
public Kecheng(String cname,double score){
this.cname=cname;
this.score=score;
}
public String getCname(){
return cname;
}
public void setCname(String cname){
this.cname=cname;
}
public double getScore(){
return score;
}
public void setScore(double score){
this.score=score;
}
}
编译出错提示为:
SortStudent.java:40: 需要 <标识符>
li.add(new Course( "英语 ",rd.nextInt(100)));
^
SortStudent.java:41: 需要 <标识符>
li.add(new Course( "物理 ",rd.nextInt(100)));
^
SortStudent.java:42: 需要 <标识符>
li.add(new Course( "化学 ",rd.nextInt(100)));
^
SortStudent.java:43: 需要 <标识符>
li.add(new Course( "语文 ",rd.nextInt(100)));
^
4 错误
请帮忙指点一下.
[解决办法]
你定义的List <Kecheng> li=new ArrayList <Kecheng> (); 要相list中添加的元素是Kecheng类的对象,而你实际添加的却是:li.add(new Course( "语文 ",rd.nextInt(100))); Course对象。
[解决办法]
这是jdk1.5添加的类型检验特性
[解决办法]
根据你的定义向li添加的必须是Kecheng类对象或者是Kecheng类的子类的对象
[解决办法]
你 Course 类导入了吗?有没有这个类,是报你说的错的直接原因
楼上说的在List <Kecheng> 只能加入Kecheng也是一个原因
总结出来你的原因,把Course改成Kecheng都行了
[解决办法]
不存在楼上说的原因,如果是Course类没有导入不是这个错误提示,
就是我说的原因,当然还有一种解决方法,就是把类型检查去掉,写成下面的
List li=new ArrayList();
这样就不会进行类型检查了,你可以向里面add任何Object
这样时候你再取li中的元素的时候就需要进行强制类型转换了。
[解决办法]
编译的问题高手都来解决,就是你的List放错了对象
[解决办法]
楼主在外面定义了一个课程类,类名用的是拼音:Kecheng,但是他在Student 类中引用课程类的时候,却使用了课程的英文名Course。编译的时候,会为认为这个类没有~
还有,楼主的
li.add(new Course( "英语 ",rd.nextInt(100)));
li.add(new Course( "物理 ",rd.nextInt(100)));
li.add(new Course( "化学 ",rd.nextInt(100)));
li.add(new Course( "语文 ",rd.nextInt(100)));
这一段,应该写在方法里
类中只能声明变量,变量的操作,应该放在方法中~
[解决办法]
有空搞