I am building a classical Nim game. So far, I've done the player part and the game part. Now, I am trying to sort(rank) the object in an array. I've built the following for sorting:
playerList
winRatio
, which is set in theNimPlayer
class with its getter.
The aim :
- to sort the
winRatio
descendingly, which means from the highest score to the lowest one. The ratio is calculated byscore/gamePlayed
. - If there's a tie, sort using
userName
alphabetically.
I've referred to this issue: How to sort an array of objects in Java?
I know what I should do is use the Comparable
or Comparator
for sorting but from the article, they sort using the attributes in the object (All the information I've found so far). What I am dealing with is the continuously updated data outside the constructor.
What I've tried was directly printed out the data without sorting.
Here is my related code (NimPlayer
):
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
static int counter;
private int score;
private int gamePlayed;
static NimPlayer[] playerList = new NimPlayer[2]; // set an array here
//define NimPlayer data type
public NimPlayer(String userName, String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName) {
if (counter<10) {
playerList[counter++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
// all the getter and setter related to the constructor; the getter of the player list.
}
public void setScore(int score) {
this.score=score;
}
public int getScore() {
return score;
}
public void setGamePlayed (int gamePlayed) {
this.gamePlayed = gamePlayed;
}
public int getGamePlayed() {
return gamePlayed;
}
public int getWinRatio () {
return Math.round(Float.valueOf(getScore())/ (getGamePlayed()+1)*100) ;
}
}
This is my main class (Nimsys
)
public static void searchAndPrintRankingData() {
for (int i = 0; i < NimPlayer.getCounter(); i++) {
String familyName = NimPlayer.getPlayer()[i].getFamilyName();
String givenName = NimPlayer.getPlayer()[i].getGivenName();
int score = NimPlayer.getPlayer()[i].getScore();
int gamePlayed = NimPlayer.getPlayer()[i].getGamePlayed();
double winRatio = score/(gamePlayed+1);//wrong calculation for testing
System.out.println(winRatio+"% | "+gamePlayed+" games | "+givenName+" "+familyName);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("rankings")) {
String commandOrder = in.nextLine().trim();
if (commandOrder.equals("asc")) {
//sort the data
searchAndPrintRankingData();
}
if (commandOrder.equals("") || commandOrder.equals("desc")) {
//sort the data
searchAndPrintRankingData();
}
}
}
Any help is highly appreciated.