+ 1

I want to print key who has max point .. it shows can not find symbol..what's wrong with this code??

import java.util.*; public class Bowling { HashMap<String, Integer> players; Bowling() { players = new HashMap<String, Integer>(); } public void addPlayer(String name, int p) { players.put(name, p); } public String getWinner (){ String w; int v, c=0; Iterator s = players.iterator(); while (s.hasNext()){ v= s.isNext(); if(v>c){ c=v; w= s.getKey(); } } return w; } } public class Program { public static void main(String[ ] args) { Bowling game = new Bowling(); Scanner sc = new Scanner(System.in); for(int i=0;i<3;i++) { String input = sc.nextLine(); String[] values = input.split(" "); String name = values[0]; int points = Integer.parseInt(values[1]); game.addPlayer(name, points); } game.getWinner();}

2nd May 2021, 11:22 AM
Ajay Mistry
Ajay Mistry - avatar
4 Respostas
+ 3
Ajay Mistry You need to change your logic of getWinner() method. Replace with this logic public void getWinner() { String maxKey = null; int maxValue = 0; Iterator<Map.Entry<String, Integer>> s = players.entrySet().iterator(); while (s.hasNext()) { Map.Entry<String, Integer> entry = s.next(); int val = entry.getValue(); if(val > maxValue) { maxValue = val; maxKey = entry.getKey(); } } System.out.println (maxKey); } ---------------- Or you can use this simple lambda logic ------------ public void getWinner() { String key = Collections.max(players.entrySet(), Map.Entry.comparingByValue()).getKey(); System.out.print(key); } https://code.sololearn.com/cwPtHMc35a4t/?ref=app 1 - isNext() returns Boolean value 2 - make understandable variable name not like that w, c
2nd May 2021, 11:51 AM
A͢J
A͢J - avatar
+ 2
Ajay Mistry can you link the code link instead of posting to increase readability and getting helpful answer
2nd May 2021, 11:44 AM
Ananiya Jemberu
Ananiya Jemberu - avatar
+ 1
or public class Bowling { HashMap<String,Integer> players; String winner; int maxScore; public String getWinner() { players.forEach( (k,v) -> { if (v > maxScore) { winner = k; maxScore = v; } }); return winner; }
2nd May 2021, 8:49 PM
zemiak
0
Sure
2nd May 2021, 11:45 AM
Ajay Mistry
Ajay Mistry - avatar