java - 编码战争并努力展示已玩过的牌
问题描述
我正在用 Java 编写 War 代码。它可以工作,除了我无法打印出打出的牌。现在我有这个:
for (int i=0; i<26; i++) {
int p1Value = player1.flip().getRank();
System.out.println("Player 1 plays the " + player1.flip().toString());
int p2Value = player2.flip().getRank();
System.out.println("Player 2 plays the " + player2.flip().toString());
System.out.println("-------------------------------------");
//compare card values & allots point to the higher one
if(p1Value > p2Value) {
player1.incrementScore();
showMessageDialog(null, "Player 1 wins the round.");//alerts w
}
else if (p2Value > p1Value) {
player2.incrementScore();
showMessageDialog(null, "Player 2 wins the round.");
}
else {
showMessageDialog(null, "It's a tie! No points awarded.");
}
}
改成这个会导致它只运行 13 次而不是 26 次(但可以运行 13 次)。在我添加 Sysouts 之前,它运行良好 26 次,但只是没有打印出牌。我最好的猜测是,每次我说玩家正在翻转时,我都会用完一张单独的牌。我试图将它分配给一个变量,希望这会有所帮助,但它没有。我对吗?我该如何解决?TIA
打印播放(玩家 1 播放 ___,玩家 2 播放 ___)13 次。然后这个错误:
线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引 0 超出长度 0 的范围
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.remove(ArrayList.java:504)
at Players.flip(Players.java:48)
at War.main(War.java:32)
解决方案
那是因为在您的 Sysout 中,您flip()
再次调用。而是将结果存储到变量中。
var result = player1.flip();
int p1Value = result.getRank();
System.out.println("Player 1 plays the " + result.toString());