The problem Write a program that prompts the user to enter the number of students and each student’s name and score, and finally displays the name of the student with the highest score .
Breaking it down public static void main ( String [] args ) {
Scanner input = new Scanner ( System . in );
System . out . print ( "Enter the number of student: " );
int studentCount = input . nextInt ();
input . nextLine ();
Map < String , Double > students = new HashMap < String , Double >();
for ( int i = 0 ; i < studentCount ; i ++) {
System . out . print ( "Enter name for student #" + ( i + 1 ) + ": " );
String name = input . next ();
System . out . print ( "Enter score for student #" + ( i + 1 ) + ": " );
double score = input . nextDouble ();
students . put ( name , score );
}
input . close ();
Comparator <? super Entry < String , Double >> maxValueComparator = ( entry1 ,
entry2 ) -> entry1 . getValue (). compareTo ( entry2 . getValue ());
Optional < Entry < String , Double >> maxValue = students . entrySet (). stream ()
. max ( maxValueComparator );
System . out . println ( "Top student " + maxValue . get (). getKey ()
+ "'s score is " + maxValue . get (). getValue ());
}
Output Enter the number of student: 3
Enter name for student #1: Jackson
Enter score for student #1: 20
Enter name for student #2: Julie
Enter score for student #2: 15
Enter name for student #3: Susan
Enter score for student #3: 32
Top student Susan's score is 32.0
Find the highest score posted by Justin Musgrove on 10 April 2016
Tagged: java, java-exercises-beginner, intro-to-java-10th-edition, and ch5
Share on: Facebook Google+