I am trying to beat a sololearn challenge where we store the name of a player in a hashmap and then I am needed to iterate through the values of each player hashmap and get the name of the player with the highest score. I have been given a template code but do not have any idea on how to complete the class Bowling with a method called getWinner() to get the name of the player with the maximum points please help
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);
}
//your code goes here
void getWinner(){
//help me complete this to get the name or the winner
}
}
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();
}
}
You get the entrySet (key, value), use a Comparator and compare them by the value and use Collections.max() to get the highest value. After this just get the key and you have the player name:
Collections.max(players.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();
You can get all key from a map with keySet() and so get the values associated to the key. So here a key would be the name of a player and the values is score.
So here is a simple answer if there is no tie :).
void getWinner(){
int currentBestScore = 0;
String currentWinner = "nobody"
for ( String playerName : players.keySet() ) {
if(players.get(playerName)>=currentBestScore){
currentWinner = playerName;
}
}
System.out.println(playerName);
}
Related
My assignment is I have to manage a soccer league.There is a soccer league (text file) that I have to import into the program.Each line of the imported file displays the outcome of a single game:the name of two teams together with the scores like
Peter 4 Tiger 3
Sky 2 Peter 0
Tiger 1 Sky 2
I have to write the program to read this text file and displays the output of team records like
Team Wins Losses
Peter 1 1
Tiger 0 2
Sky 2 0
I don't understand how to read through the lines and calculate the wins and losses associated with each team/String.
import java.util.*;
import java.io.*;
public class SoccerLeagueStandings
{
public static void main(String[] args) throws IOException
{
File inFile = new File("LeagueScore.txt");
if(! inFile.exists())
{
System.out.println("Error could not open the file");
return;
}
String Panthers="Panthers";
String Tigers = "Tigers";
String Sky = "Sky";
Scanner input = new Scanner (inFile);
int PW=0;
int PL=0;
int TW =0;
int TL = 0;
int SW=0;
int SL=0;
while (input.hasNextLine())
{
String firstTeam=input.next();
input.nextInt();
int firstScore=input.nextInt();
String secondTeam=input.next();
input.nextInt();
int secondScore = input.nextInt();
if (firstScore>secondScore)
{
if (firstTeam.equals(Panthers))
{
PW+=1;
}
if (firstTeam.equals(Tigers))
{
TW+=1;
}
if (firstTeam.equals(Sky))
{
SW+=1;
}
}
}
}
}
The main challenge in this problem is to keep track of the wins and losses of each team.
So i suggest to create a class called Team which holds: name, winsCount, lossCount. This class represents a single team along with its wins and loss count.
Create an arrayList of Team and fill it using the file content.
So your algorithm would be as the following:
Parse the file line by line using Scanner.
Split each line by space in order to get the teams and their scores.
Compare the scores of the teams.
Add the winner team to the ArrayList OR increment its winsCount if already exist.
Do the same for the loser team.
Below is a non-tested sample code:
Following is the Team class:
public class Team {
private String name;
private int winsCount;
private int lossCount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWinsCount() {
return winsCount;
}
public void setWinsCount(int winsCount) {
this.winsCount = winsCount;
}
public int getLossCount() {
return lossCount;
}
public void setLossCount(int lossCount) {
this.lossCount = lossCount;
}
}
Below is how to fill the arraylist from the input file:
private void generateWinsLossesFromInput(String filePath)
{
Scanner input = new Scanner(filePath);
List<Team> teams = new ArrayList<Team>();
while(input.hasNext())
{
String match = input.next();
// Split the line and get teams and their scores.
String[] splittedMatch = match.split("\\s+");
String firstTeam = splittedMatch[0];
int firstTeamScore = Integer.parseInt(splittedMatch[1]);
String secondTeam = splittedMatch[2];
int secondTeamScore = Integer.parseInt(splittedMatch[3]);
if(firstTeamScore > secondTeamScore)
{
addWinner(firstTeam, teams);
addLoser(secondTeam, teams);
}
else
{
if(secondTeamScore > firstTeamScore)
{
addWinner(secondTeam,teams);
addLoser(firstTeam, teams);
}
}
}
}
private void addWinner(String team, List<Team> teams)
{
int index = 0;
for(index = 0; index<teams.size(); index++)
{
Team t = teams.get(index);
if(t.getName().equalsIgnoreCase(team))
{
// Team already exists, so just increment its winsCount
t.setWinsCount(t.getWinsCount() + 1);
break;
}
}
if(index == teams.size())
{
// team not found, So add it as new team to the list.
Team t = new Team();
t.setName(team);
t.setWinsCount(1);
t.setLossCount(0);
teams.add(t);
}
}
private void addLoser(String team, List<Team> teams)
{
int index = 0;
for(index = 0; index<teams.size(); index++)
{
Team t = teams.get(index);
if(t.getName().equalsIgnoreCase(team))
{
// Team already exists, so just increment its loss count.
t.setLossCount(t.getLossCount() + 1);
break;
}
}
if(index == teams.size())
{
// team not found , then add new team to the list
Team t = new Team();
t.setName(team);
t.setWinsCount(0);
t.setLossCount(1);
teams.add(t);
}
}
At the end, you would be able to iterate over the array list and print out each team along with its Wins and loss counts.
I am trying to create a method which creates a result for a athlete in a competition. I have an ArrayList with the athletes in another class and now I want this method to be able to find the size of the ArrayList and also compare one int attribute of every Athlete with the input number. This is what I have so far, Im really stuck. So my quetions to you are: How do I get my for loop to see the size of the ArrayList athletes? and what is a proper way to check whether or not the input has a matching athlete in the ArrayList(I want it to print out if there is no match)? Thank you
public class ResultList {
Scanner scanner = new Scanner(System.in);
ArrayList<Result> resultList = new ArrayList<Result>();
public ResultList() {
ArrayList<Athlete> temp = new AthleteList().getArrayList();
}
void addResult() {
int competetionNumber;
System.out.print("What is the athletes competetionnumber?");
competetionNumber = scanner.nextInt();
scanner.nextInt();
for (int i = 0; i < athletes.size(); i++) {
}
}
}
Other class with the Athlete ArrayList:
public class AthleteList {
ArrayList<Athlete> athletes = new ArrayList<Athlete>();
public AthleteList () {
}
public ArrayList<Athlete> getArrayList() {
return athletes;
}
You should create a variable that points to the AthleteList class. Then you can see that in the addResult method you just get the ArrayList from the AthleteList and call size() on it and iterate over the Athletes and check the completionNumber(You didn't post the Athlete class so I'm assuming there is a completionNumber property). I create a matched variable to hold on to the matched Athlete. After the loop I check to see if one matched and print out the result.
Hope this helps.
public class ResultList
{
Scanner scanner = new Scanner(System.in);
ArrayList<Result> resultList = new ArrayList<Result>();
AthleteList athleteList;
public ResultList()
{
athleteList = new AthleteList();
}
void addResult()
{
int competetionNumber;
System.out.print("What is the athletes competetionnumber?");
competetionNumber = scanner.nextInt();
scanner.nextInt();
Athlete matched = null;
List<Athlete> athletes = athleteList.getArrayList();
for(int i = 0; i < athletes.size(); i++)
{
if(athlete.completionNumber == completionNumber)
{
//you found a match!!
matched = athlete;
}
}
if(matched == null)
{
System.out.println("No Match Found for " + completionNumber);
}
else
{
System.out.println("Found match: " + matched.toString());
}
}
}
NOTE:
Not sure you need the AthleteList class. It's just holding an ArrayList. If that's all that class will ever do then I suggest you just using an ArrayList. It will make your code cleaner.
I have been stuck on this problem for so long and i have no idea what to do.
Basically i have a text file with people names then student number then prize money like this:
Green%3243%1000
Kevin%7657%400
Frank%345%10000
Bob%5435%5000
Stefan%31231%1000
Javis%4532%100
IronMan%5435%2000
Lamp%534%3000
What i want to be able to do is sort the array based on the last number.
I tried this abomination (Don't bother reading it its garbage):
boolean flag = true;
String temp;
int temp1;
int temp2;
while (flag){
flag = false;
for(int j=0; j < list.size() -1; j++ ){
System.out.println(list.get(j));
Scanner s = new Scanner(list.get(j)).useDelimiter("%");
s.next();
s.next();
temp1 = s.nextInt();
Scanner s2 = new Scanner(list.get(j+1)).useDelimiter("%");
s2.next();
s2.next();
temp2 = s2.nextInt();
if (temp1 < temp2){
temp = list.get(j);
list.add(j, list.get(j+1));
list.add(j+1,temp);
flag = true;
}
}
}
But its just infinitely looping. My though while making it was just patching array lists into a bubble sort.
If anyone has any ideas and is willing to share them it will be greatly appreciated.
Java is an object-oriented language, so I'll just use objects:
Create a Student object with the three values you want to store (and a toString() method to print them separated by "%":
public class Student {
private final String name;
private final int number;
private final int prizeMoney;
public Student(final String name, final int number, final int prizeMoney) {
this.name = name;
this.number = number;
this.prizeMoney = prizeMoney;
}
#Override
public String toString() {
return name+"%"+number+"%"+prizeMoney;
}
public int getPrizeMoney() {
return prizeMoney;
}
}
Read your lines as Student objects, and store them in a List:
final Scanner scan = new Scanner(new File("/path/to/StudentsList"));
final List<Student> students = new ArrayList<Student>();
while (scan.hasNextLine()) {
final Scanner line = new Scanner(scan.nextLine());
line.useDelimiter("%");
students.add(new Student(line.next(), line.nextInt(), line.nextInt()));
line.close();
}
scan.close();
Order the List with a custom Comparator, and print it:
students.sort(new Comparator<Student>() {
#Override
public int compare(final Student s1, final Student s2) {
return s1.getPrizeMoney()-s2.getPrizeMoney();
}
});
for (final Student student: students)
System.out.println(student);
Output:
Javis%4532%100
Kevin%7657%400
Green%3243%1000
Stefan%31231%1000
IronMan%5435%2000
Lamp%534%3000
Bob%5435%5000
Frank%345%10000
Here's something for you to get head started.
Create a map for prize money => line as key/value pair
Read each line in the file, parse it and put key/value pair in the above map
Once your map is ready, convert the keys entry set into the collections like list
Sort the collections, using Collections.sort()
Iterate over the created map, and for each value in the collection get the corresponding value from the map.
Hope this helps you to get the workflow.
Id consider creating a 3d array here 8x8x8 from right to left in the array is row, col, and in so [0][0][1] is block one or kevin [0][1][1] is 7657 [1][1][1] is 400. I like this way because not only does it give each 'item' an array it allows you to keep it organized and easily accessable
My hashmap contains a key which is the customers name, and the values are all the ratings for the books rated. I have to calculate the average rating for a given booktitle.
How do I access all of the values (ratings) from the hashmap? Is there a method for doing this?
Here is a piece of my code:
/**
* calculate the average rating by all customers for a named book
* only count positive or negative ratings, not 0 (unrated)
* if the booktitle is not found or their are no ratings then
* return NO_AVERAGE
* #param booktitle String to be rated
* #return double the average of all ratings for this book
*/
public double averageRating(String booktitle)
{
numberOfRatingsPerCustomer/total
}
You need to get the keySet from the HashMap. And then Iterate over the keySet and fetch the values from the HashMap.
Your question makes no sense.
You can't have a map with customerName to hisRatingOfBook, and search in it for bookTitle. You need to go one of 1 ways:
1)
create method public double averageRating() inside Book class, and keep there, as field, rating being map with customerName to hisRatingOfBook
2) Use your method:
public double averageRating(String booktitle)
{
numberOfRatingsPerCustomer/total
}
but make your map something more complex, that will hold customer, and its rating (being made from book title + rate)
Here you go take these below code it will help you out to find your rating problem
I have done to find average of Student marks in a class
import java.util.*;
public class QueQue {
public static float getAverage(HashMap<String, ArrayList<Integer>> hm, String name) {
ArrayList<Integer> scores;
scores = hm.get(name);
if (scores == null) {
System.out.println("NOT found");
}
int sum = 0;
for (int x : scores) {
sum += x;
}
return (float) sum / scores.size();
}
public static void main(String[] args) {
HashMap<String, ArrayList<Integer>> hm = new HashMap<>();
hm.put("Peter", new ArrayList<>());
hm.get("Peter").add(10);
hm.get("Peter").add(10);
hm.get("Peter").add(10);
hm.put("Nancy", new ArrayList<>());
hm.get("Nancy").add(7);
hm.get("Nancy").add(8);
hm.get("Nancy").add(8);
hm.put("Lily", new ArrayList<>());
hm.get("Lily").add(9);
hm.get("Lily").add(9);
hm.get("Lily").add(8);
System.out.println("Find the average of the Peter");
float num = getAverage(hm, "Peter");
}
}
This simple game asks for the number of the players and their names and counts their score.How can i get the player with the highest score?
main:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
HashMap<String,Integer> players= new HashMap<String,Integer>();
System.out.printf("Give the number of the players: ");
int numOfPlayers = scanner.nextInt();
for(int k=1;k<=numOfPlayers;k++)
{
System.out.printf("Give the name of player %d: ",k);
String nameOfPlayer= scanner.next();
players.put(nameOfPlayer,0);//score=0
}
//This for finally returns the score
for(String name:players.keySet())
{
System.out.println("Name of player in this round: "+name);
//::::::::::::::::::::::
//::::::::::::::::::::::
int score=players.get(name)+ p.getScore();;
//This will update the corresponding entry in HashMap
players.put(name,score);
System.out.println("The Player "+name+" has "+players.get(name)+" points ");
}
}
This what i tried myself:
Collection c=players.values();
System.out.println(Collections.max(c));
You can use Collections.max() to get the maximum value of the Collection of hashmap entries obtained by HashMap.entrySet() with custom comparator for comparing values.
Example:
HashMap<String,Integer> players= new HashMap<String,Integer>();
players.put("as", 10);
players.put("a", 12);
players.put("s", 13);
players.put("asa", 15);
players.put("asaasd", 256);
players.put("asasda", 15);
players.put("asaws", 5);
System.out.println(Collections.max(players.entrySet(),new Comparator<Entry<String, Integer>>() {
#Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
}));
You can modify above code to best meet your condition.