【发布时间】:2020-08-07 15:54:49
【问题描述】:
我正在构建一个经典的 Nim 游戏。到目前为止,我已经完成了玩家部分和游戏部分。现在,我正在尝试对数组中的对象进行排序(排名)。我为排序构建了以下内容:
playerList-
winRatio,在NimPlayer类及其 getter 中设置。
目标:
- 对
winRatio进行降序排序,即从最高分到最低分。该比率由score/gamePlayed计算得出。 - 如果出现平局,请使用
userName按字母顺序排序。
我已经提到过这个问题:How to sort an array of objects in Java?
我知道我应该做的是使用Comparable 或Comparator 进行排序,但从文章中,他们使用对象中的属性进行排序(到目前为止我找到的所有信息)。我正在处理的是构造函数之外不断更新的数据。
我试过的是不排序直接打印出来的数据。
这是我的相关代码(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) ;
}
}
这是我的主要课程 (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();
}
}
}
非常感谢任何帮助。
【问题讨论】:
-
你应该先看看 java 集合框架,如果你不必自己实现的话,已经有很多符合你期望的数据结构实现了。
-
感谢您的推荐。我试图在不使用
ArrayList的情况下处理它。当然,ArrayList可以节省很多时间和精力。