Give a record a natural order and let Arrays.sort do the ranking.
What to build
A program that ranks players by score.
Requirements
- Write
record Player(String name, int score)implementingComparable<Player>: higher scores first, equal scores in alphabetical order of name. - Sort an array of players with
Arrays.sortand printR. NAME (SCORE)for each.
Input
Line 1: n. Then n lines NAME SCORE.
Output
n lines.
Constraints
1 ≤ n ≤ 100; names are distinct single words; 0 ≤ score ≤ 10^9.
Example
Input:
3
Rina 72
Arif 88
Zoya 80
Output:
1. Arif (88)
2. Zoya (80)
3. Rina (72)
Why it works
compareTo encodes the ranking rule once, with Integer.compare avoiding overflow, and every sort of players then follows it.
Examples
Example 1 · Input
3 Rina 72 Arif 88 Zoya 80
Expected output
1. Arif (88) 2. Zoya (80) 3. Rina (72)
Example 2 · Input
3 cara 50 bob 50 ali 70
Expected output
1. ali (70) 2. bob (50) 3. cara (50)
Hints
Hint 1
record Player(String name, int score) implements Comparable<Player>; compare scores first (higher first), then names.
Hint 2
Arrays.sort(players) then uses your compareTo.
Solution
Show one correct solution (try it yourself first)
import java.util.Arrays;
import java.util.Scanner;
record Player(String name, int score) implements Comparable<Player> {
public int compareTo(Player o) {
int byScore = Integer.compare(o.score, score);
return byScore != 0 ? byScore : name.compareTo(o.name);
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Player[] players = new Player[n];
for (int i = 0; i < n; i++) players[i] = new Player(in.next(), in.nextInt());
Arrays.sort(players);
for (int i = 0; i < n; i++) System.out.println((i + 1) + ". " + players[i].name() + " (" + players[i].score() + ")");
}
}