Java
自定义对象(重点)。自定义Student类,包含学号(整型)和成绩(浮点型)两个属性,请设计可初始化两个属性的构造函数,并在main函数中任意实例化10个Student对象放入List,按学号升序排序后,依次逐行在控制台通过重写后toString()输出学号xxx同学的成绩为xxx。
package asdasd;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class student {
private int ID;
private double score;
public student() {}
public student(int ID,double score) {
// TODO Auto-generated constructor stub
this.ID = ID;
this.score = score;
}
public int GetID() {
return this.ID;
}
public double GetScore() {
return this.score;
}
@Override
public String toString() {
return "学号为"+ID+"同学的成绩为"+score;
}
}
class MyCompare implements Comparator<student>{
@Override
public int compare(student o1, student o2) {
// TODO Auto-generated method stub
double s1 = o1.GetScore();
double s2 = o2.GetScore();
if(s1>s2)
return 1;
return 0;
}
}
public class Mine {
public static void main(String[] args) {
List<student> sList = new ArrayList<>();
for(int i=0;i<10;i++) {
student students = new student(i,(i*1.2+123.3)/2.3);
sList.add(students);
}
Collections.sort(sList,new MyCompare());
for(student ssStudent:sList) {
System.out.println(ssStudent);
}
}
}