如何在 java 中对胜率进行排名



我一直在用三个java类构建一个经典的Nim游戏。到目前为止,我几乎构建了所有东西,我需要做的最后一件事就是按winning ratio降序对玩家进行排名,这是score除以gamePlayed。我尝试的是NimPlayer类中实现可比性。这是我的代码:

public class NimPlayer implements Comparable<NimPlayer>{ //initialize comparable
private String userName;
private String familyName;
private String givenName;
static int counter;
private int score;
private int gamePlayed;
private int winRatio = score / (gamePlayed+1); //avoid 0/0, mathmatically wrong
static NimPlayer[] playerList = new NimPlayer[10]; // 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.");
}
}
public static int getCounter() {
return counter;
}
public static NimPlayer [] getPlayer() {
return playerList;
}
// the getter and the setter of userName, familyName, givenName, score, gamePlayed
@Override
public String toString() {
return winRatio+"% | "+gamePlayed+" games | "+givenName+" "+familyName;
}
@Override
public int compareTo(NimPlayer o) {
return this.winRatio - o.winRatio;
}
}

在调用Nimsys的主方法中,我尝试过:

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")) {
Arrays.sort(NimPlayer.getPlayer());//sorting with the object type           
System.out.println(Arrays.toString(NimPlayer.getPlayer()));
}          
}

但是,当我有两个玩家在玩并且他们的scoregamePlayed不为空时,执行仍然NullPointerException。任何帮助都非常感谢。

您得到的错误是因为您正在初始化大小为 10 的数组。排序操作将遍历所有 10 个位置,其中一些位置将为 null。如果您创建 10 个玩家,那么它应该可以正常工作。

若要具有动态大小,请改用ArrayList,并更新以下内容:

static List<NimPlayer> playerList = new ArrayList<>();
public static void createPlayer(String userName, String familyName, String givenName) {
if (counter < 10) {
playerList.add(new NimPlayer(userName, familyName, givenName));
counter++;
} else {
System.out.println("Cannot add more players.");
}
}

要对列表进行排序:

Collections.sort(NimPlayer.playerList);

除此之外,我认为您的代码中还有一些缺陷。

首先,您正在初始化字段声明中的 winRatio,至少从我在代码中看到的内容来看,永远不会更新,因此它将始终为 0。克服此问题的一种方法是在每次请求值时使用 getter 和 setter 触发计算。

public Float getWinRatio() {
return Float.valueOf(getScore()) / (getGamePlayed() + 1);
}

其次,您将 winRatio 设置为int。这将忽略除法中的所有小数,因此结果将不准确。

此外,您似乎将玩家的数据与游戏的逻辑相结合。您应该将NimPlayer类从包含游戏中所有玩家的逻辑中分离出来。

最新更新