0

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?

vm _1_r
  • 61
  • 7
  • Make sure to consume the newline with `sc.nextLine()` after a call to `sc.nextInt()`. – sleepToken Mar 09 '20 at 11:01
  • Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – sleepToken Mar 09 '20 at 11:01

1 Answers1

1

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();