Sort An Array Of Objects containing Strings and Integers | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Sort An Array Of Objects containing Strings and Integers

I want user to input the number of players[2-16] in the game.Each user will have a name and an Id. Each player will throw dice twice and the product of each dice will determine player's score E.g: 5*6=30 so player1 has a score of 30.In the end I want to display the player who has the highest score. I have made an array of objects to store the name and ID and also their score .Now how can I compare players to get the highest scorer?

29th Sep 2017, 9:20 PM
Usama Zafar
Usama Zafar - avatar
2 Answers
+ 4
I suggest making each Player their own Object, with ID, name and score as their instance variables. But, encase you haven't gotten to the OOP side of Java yet: It sounds like you have one array that holds all the information. Something like: Object[] array; If the ID is an int, you will need some pattern to know which index of the array is the players score. Let's say for example, index 0 is the players name, index 1 is that players ID, and index 2 is that players score. Index 3 will begin the next Player. So, all we would care about is every 3rd index. Since we want to find out who has the highest score, we will go through the entire array to find it. int highestScore = 0; String player = null; for(int i = 2; i < array.length(); i += 3) if(array[i] > highestScore) { highestScore = array[i]; player = array[i - 2]; } // found new highest Once this loop is complete, you will have the highest score. 'player' would be the persons name with the highest score and 'highestScore' would be that score. If you did not use an Object array and made 3 separate arrays for each attribute, the idea is the same. However, you would increment i by 1 instead of 3. Since there's no need to skip over the name/id in an array that only has scores.
29th Sep 2017, 11:24 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
This is not relevant to my question
29th Sep 2017, 9:59 PM
Usama Zafar
Usama Zafar - avatar