- /**键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低输出到控制台。 */
- Scanner sc = new Scanner(System.in);
- TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>(){
-
- public int compare(Student o1, Student o2) {
- int result = o2.getScore()-o1.getScore();
- return result==0?-1:result;
- }
- });
-
- System.out.println("请输入学生信息,格式:姓名,语文成绩,数学成绩,英语成绩");
- for(int i=0;i<5;i++){
- String line = sc.nextLine();
- try {
- String[] arr = line.split(",");
- int c = Integer.parseInt(arr[1]);
- int m = Integer.parseInt(arr[2]);
- int e = Integer.parseInt(arr[3]);
- ts.add(new Student(arr[0], c, m, e));
- } catch (Exception e) {
- System.out.println("输入格式不正确,请重新输入!");
- System.out.println("格式:姓名,语文成绩,数学成绩,英语成绩");
- i--;
- }
- }
- for(Student s:ts){
- System.out.println(s);
- }
-
-
- }
- }
- class Student {
- String name;
- int chinese;
- int math;
- int english;
-
-
- public Student(String name, int chinese, int math, int english) {
- super();
- this.name = name;
- this.chinese = chinese;
- this.math = math;
- this.english = english;
- }
-
-
- @Override
- public String toString() {
- return "Student [name=" + name + ", chinese=" + chinese + ", math=" + math + ", english=" + english + "]";
- }
- public int getScore(){
- return chinese+math+english;
- }
- }
复制代码 |
|