3-5 编程练习报错
来源:3-5 编程练习
慕仰2259325
2021-01-30 23:04:57
问题描述:
我运行编程练习,报错如下,请问哪里有问题?
相关代码:
//实现Comparator接口
public class StudentTest implements Comparator<Student>{
//实现接口中的方法
public int compare(Student s1, Student s2){
String name1 = s1.getName();
String name2 = s2.getName();
return name1.compareTo(name2);
}
public static void main(String[] args){
//定义Student类的对象
Student s1 = new Student(40,20,"peter");
Student s2 = new Student(28,5,"angel");
Student s3 = new Student(35,18,"tom");
//将对象添加到List中
List<Student> list = new ArrayList<Student>();
list.add(s1);
list.add(s2);
list.add(s3);
//输出排序前的数据
System.out.println("按名字排序前:");
for(Student s:list){
System.out.println(s);
}
//排序
Collections.sort(list, new StudentTest());
//输出排序后的数据
System.out.println("按名字排序后:");
for(Student s:list){
System.out.println(s);
}
}
}
public class Student {
//成员变量
private int num;
private int age;
private String name;
//构造方法
public Student(){};
public Student(int num, int age, String name){
this.setNum(num);
this.setAge(age);
this.setName(name);
}
//getter和setter方法
public void setNum(int num){
this.num = num;
}
public int getNum(){
return this.num;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
//toString()方法
public String toString(){
return "[学号:"+this.getNum()+", 年龄:"+this.getAge()+", 姓名:"+this.getName()+"]";
}
}
相关截图:

1回答
同学你好,测试运行上述代码是正确的,出现报错是因为同学没有进行导包操作,修改代码如下:
祝学习愉快~
相似问题