编写一个程序,用户键盘录入若干个学生的姓名和分数(程序每次提示用户输入“Y”或“N”决定是否继续录入学生信息,如果用户输入“N”则用户输入完毕。输入的“Y”、“N”不区分大小写)。
用户录入完毕后,程序按成绩由高到低的顺序输出学生的姓名和分数(姓名和分数之间用一个空格分割)。
【说明:键盘输入可以使用Scanner类】
package T1;
import java.lang.reflect.Array;
import java.util.*;
public class StudentGrade {
class MyComparator implements Comparator<Student>{
public int compare(Student o1, Student o2) {
if(o1.getGrade() < o2.getGrade())
return 1;
else if(o1.getGrade() > o2.getGrade())
return -1;
else
return 0;
}
}
public static void main(String[] args) {
ArrayList list = new ArrayList();
Scanner sc = new Scanner(System.in);
System.out.println("是否继续录入学生信息?(Y/N)");
while(true){
String yn = sc.nextLine();
if(yn.equals("y")||yn.equals("Y")){
System.out.println("请输入姓名和成绩:");
String na = sc.nextLine();
double gra = sc.nextDouble();
//sc.nextLine();
list.add(new Student(na,gra));
System.out.println("是否继续录入学生信息?(Y/N)");
}
else if(yn.equals("N")||yn.equals("n")){
break;
}
//System.out.println("是否继续录入学生信息?(Y/N)");
}
StudentGrade s = new StudentGrade();
MyComparator myCom = s.new MyComparator();
Collections.sort(list, myCom);
System.out.println(list.toString() + " ");
}
}
class Student{
private String name;
private double grade;
Student(String n, double g){
this.name = n;
this.grade = g;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
public String toString(){
String result = getName() + " "+ getGrade();
return result;
}
}