简体   繁体   中英

HashMap getting Inputted Sorted Values + printing the highest value as String and Integer

I am writing a program that asks to enter a number of students, student's name and his scores. Then the program must sort values and output the best student in the class(with mark greater than 4 let's say 5). I cannot output student's name . The program prints out the score it also sorts the values but doesn't print the String type value.

HashMap <String,Integer> student = new HashMap <String,Integer> (); 
        System.out.println("Enter a number of students: ");
        int numberOfStudents = sc.nextInt();

        String a ="";

        Integer b = 0;

          for(int i=0; i<numberOfStudents; i++){
            System.out.println("Enter a student's name");
              a=sc.next();
                  System.out.println("Enter the student's score");
                     b=sc.nextInt();
                          student.put(a, b);

 }
   student.entrySet()
  .stream()
  .sorted(HashMap.Entry.<String, Integer>comparingByKey())
  .forEach(System.out::println);
        if(b>4)
    System.out.println("The best student is "+student.get(a));/*Here "a" is a string,isn't it? Firstly ,
I tried to get the values of both String and Integer by writing student.get(a,b); But the program
throws Exceptions saying "no suitable method found for get(String , Integer)".*/

Here is the output:

Enter a number of students: 
2
Enter a student's name
N
Enter the student's score
4
Enter a student's name
d
Enter the student's score
5
N=4
d=5
The best student is 5

Why does the program display "a"(String) as an Integer and when switching a to b(Integer) it displays null? And how can i finally display the best student's name and his score?

In HashMap the first value is the key and the second value is associated with the key.

HashMap <String,Integer> student = new HashMap <String,Integer> (); 

Here the String is the key, that means the HashMap is sorted according to the String and not Integer as desired. Try using the following,

HashMap <Integer, String> student = new HashMap <String,Integer> (); 

student.get(a) gives you the value corresponding to the key a , that is why you got Integer output in your case.

Try using getKey() and getValue() to retrieve the key and value.

String key = entry.getKey();


String value = entry.getValue();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM