1、要求:
键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低输出到控制台
2、示例代码如下:
package com.jh.www;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
public class Test10 {
public static void main(String[] args) {
/*键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低输出到控制台
*分析
*
* **/
TreeSet<Stud> ts = new TreeSet<>(new Comparator<Stud>() {
public int compare(Stud s1, Stud s2) {
int num = s2.getScore_total() - s1.getScore_total();
return num == 0 ? 1 : num;
}
});
Scanner sc = new Scanner(System.in);
for(int i=0; i<5;i++) {
System.out.println("请输入学生信息:姓名,语文成绩,数学成绩,英语成绩");
String str = sc.nextLine();
String[] arr = str.split(",");
int chinese = Integer.parseInt(arr[1]);
int math = Integer.parseInt(arr[2]);
int english = Integer.parseInt(arr[3]);
ts.add(new Stud(arr[0],chinese,math,english));
}
System.out.println(ts);
for(Stud s:ts) {
System.out.println(s);
}
}
}
class Stud {
private String name;
private int score_ch;
private int score_ma;
private int score_en;
private int sum;
public Stud() {
super();
// TODO Auto-generated constructor stub
}
public Stud(String name, int score_ch, int score_ma, int score_en) {
super();
this.name = name;
this.score_ch = score_ch;
this.score_ma = score_ma;
this.score_en = score_ma;
this.sum = score_ch + score_ma+ score_ma;
}
public int getScore_total() {
return sum;
}
@Override
public String toString() {
return "Student [name=" + name + ", score_ch=" + score_ch + ", score_ma=" + score_ma + ", score_en=" + score_en
+ "]";
}
}