+ 1

Please what is the error In my code

I need the print the value of the largest key key in a hash map players https://code.sololearn.com/ca2a73A22a19/?ref=app

14th Feb 2021, 11:29 AM
Amal Gil
Amal Gil - avatar
4 Respostas
+ 3
Amal Gil You are comparing each value with next value. On every iteration you are assigning value in max value then comparing with next value.In this way you can't get max value. You have to consider first value as max value and compare with others. HashMap key is string but you are using Integer to get value. Your output should be Player's name not player's value You can try this to get name public void getWinner(){ Iterator<String> it = players.keySet().iterator(); String name = it.next(); Integer max = players.get(name); while(it.hasNext()) { String name1 = it.next(); Integer val = players.get(name1); if (val > max) { max = val; name = name1; } } System.out.print(name); } Or you can use this public void getWinner() { String key = Collections.max(players.entrySet(), Map.Entry.comparingByValue()).getKey(); System.out.print(key); }
14th Feb 2021, 12:44 PM
A͢J
A͢J - avatar
14th Feb 2021, 1:29 PM
Amal Gil
Amal Gil - avatar
+ 1
what about this one
14th Feb 2021, 1:29 PM
Amal Gil
Amal Gil - avatar
+ 1
Amal Gil This is also good but there is little mistake so here is correction public void getWinner(){ int max=Collections.max(players.values()); for(java.util.Map.Entry<String,Integer> iter:players.entrySet()){ if(iter.getValue()==max) System.out.println(iter.getKey()); } }
14th Feb 2021, 1:39 PM
A͢J
A͢J - avatar