【exam answer 1】

题目描述:
输入的第一行为n(n<40),表示有n个同学,接下来的n行每行有4个输入,分别为该学生的名字,语、数、外成绩,请按照排序规则对学生进行排序,规则如下:
1、总成绩高的排在前面 
2、总成绩相同的情况下,语文成绩高的排在前面。
3、在总成绩,语文成绩都相同的情况下,数学成绩高的排在前面。 4、在成绩都相同的情况下,先输入的同学排在前面。

参考答案:
package package01;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;

/**
 * 题目描述:
 * 输入的第一行为n(n<40),表示有n个同学,接下来的n行每行有4个输入,分别为该学生的名字,语、数、外成绩,请按照排序规则对学生进行排序,规则如下:
 * 1、总成绩高的排在前面 
* 2、总成绩相同的情况下,语文成绩高的排在前面。
* 3、在总成绩,语文成绩都相同的情况下,数学成绩高的排在前面。 * 4、在成绩都相同的情况下,先输入的同学排在前面。 * * 例如依次输入: * 3 * aa 70 80 75 * bb 80 85 90 * cc 60 65 88 * */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int input = sc.nextInt(); func(input, sc); } public static void func(int input, Scanner sc) { if (input >= 1 && input <= 40) { String[] arr = new String[input + 1]; TreeMap<String, Integer> map = new TreeMap<>(); for (int i = 0; i < input + 1; i++) { arr[i] = sc.nextLine(); } for (int i = 1; i < arr.length; i++) { int chinese = Integer.parseInt(arr[i].split(" ")[1]); int math = Integer.parseInt(arr[i].split(" ")[2]); int english = Integer.parseInt(arr[i].split(" ")[3]); int totalScore = chinese + math + english; map.put(i + "," + arr[i], totalScore); } List<Entry<String, Integer>> arrayList = new ArrayList<>(map.entrySet()); Collections.sort(arrayList, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { // 降序 if (o2.getValue().compareTo(o1.getValue()) != 0) { return o2.getValue().compareTo(o1.getValue()); } else { int chinese1 = Integer.parseInt(o1.getKey().split(" ")[1]); int chinese2 = Integer.parseInt(o2.getKey().split(" ")[1]); if (chinese2 < chinese1) { return -1; } else if (chinese1 > chinese2) { return 1; } else { int math1 = Integer.parseInt(o1.getKey().split(" ")[2]); int math2 = Integer.parseInt(o2.getKey().split(" ")[2]); if (math2 < math1) { return -1; } else if (math1 > math2) { return 1; } else { int english1 = Integer.parseInt(o1.getKey().split(" ")[3]); int english2 = Integer.parseInt(o2.getKey().split(" ")[3]); if (english2 < english1) { return -1; } else if (english2 > english1) { return 1; } else { int p1 = Integer.parseInt(o1.getKey().split(",")[0]); int p2 = Integer.parseInt(o2.getKey().split(",")[0]); if (p2 < p1) { return -1; } else { return 1; } } } } } } }); for (Entry<String, Integer> tmp : arrayList) { System.out.println(tmp.getKey().split(",")[1]); } } else { System.err.println("输入的同学个数有误,请重新输入!"); sc = new Scanner(System.in); input = sc.nextInt(); func(input, sc); } } }

  

posted @ 2020-03-01 23:46  尐鱼儿  阅读(128)  评论(0编辑  收藏  举报