The problem
Write a program that prompts the user to enter the number of students, the students’ names, and their scores, and prints student names in decreasing order of their scores.
Breaking it down
static class Student {
private String name;
private double score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int size = input.nextInt();
List<Student> students = new ArrayList<>();
for (int i = 0; i < size; i++) {
Student student = new Student();
System.out.print("Enter student #" + (i + 1) + " name: ");
student.setName(input.next());
System.out.print("Enter student #" + (i + 1) + " score: ");
student.setScore(input.nextDouble());
students.add(student);
}
input.close();
students.stream()
.sorted((e1, e2) -> Double.compare(e1.getScore(), e2.getScore()))
.forEach(
e -> System.out.println("Name: " + e.getName()
- " & score: " + e.getScore()));
}
Output
Enter the number of students: 2
Enter student #1 name: Jack
Enter student #1 score: 87
Enter student #2 name: Jimmy
Enter student #2 score: 22
Name: Jimmy & score: 22.0
Name: Jack & score: 87.0