基本上,我正在制作Nim游戏,并且在游戏的前2个序列之后代码停止循环。首先是玩家取出石头,然后是计算机取出石头。我正在尝试使其始终重复循环,直到结石达到0。为了解决此问题,我需要在哪里更改while语句?
import java.util.Scanner;
import java.lang.Math;
public class Nim {
public static int validEntry2(int comp) {
int cm = 1;
int newStones = 1;
while (cm == 1) {
comp = drawStones(comp);
if ( comp < 1 || comp > 3 || comp < newStones) {
System.out.println("Invalid parameters. Please enter something between 1-3.");
} else
System.out.println("Computer picks " + comp + " stones");
cm = 2;
}
return comp;
}
public static int validEntry(int player) {
int pl = 1;
int newStones = 1;
while (pl == 1) {
player = playerStones(player);
if (player < 1 || player > 3 || player < newStones) {
System.out.println("Invalid parameters. Please enter something between 1-3.");
} else
pl = 2;
}
return player;
}
public static int drawStones(int comp) {
comp = (int)(3 * Math.random() + 1);
return comp;
}
public static int playerStones(int player) {
Scanner input = new Scanner(System.in);
System.out.println("How many stones do you want to take?");
player = input.nextInt();
return player;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int stones;
stones = (int)(16 * Math.random() + 15);
int newStones = stones;
int player = 1;
int comp = 1;
int pl = 1;
// Display how many stones there are.
System.out.println("There are currently " + stones + " stones left");
//Players turn
while (pl == 1) {
player = validEntry(player);
if ( (newStones - player) < 0 ) {
System.out.println("Invalid input.");
} else {
pl = 2;
newStones -= player;
}
// Does the player lose?
if (newStones == 0) {
System.out.println("You just lost to a computer.");
} else {
System.out.println("There are " + newStones + " stones left");
}
// Computer Turn
int cm = 1;
while (cm == 1) {
comp = validEntry2(comp);
if ( (newStones - comp) < 0) {
System.out.println("Invalid Input.");
} else {
cm = 2;
newStones -= comp;
}
// Does Computer Lose?
if (newStones == 0) {
System.out.println("You just beat the computer!");
} else {
System.out.println("There are " + newStones + " stones left");
}
}
}
}
}
答案 0 :(得分:1)
您的第一个if's else子句没有{},因此总是执行cm = 2并立即中断while循环。
由于代码的这一部分已缩进,我强烈怀疑这不是您的意图吗?
编辑:只要pl
设置为1,您的主函数就会运行while循环。一旦pl
设置为2,该循环就会退出并因此终止程序。因此,您可能想考虑此循环的退出条件。
总的来说,我需要改进一些方面,以使调试代码更加容易。例如,与其在主函数中嵌套两个while循环,不如将它们依次执行(理想情况下是在单独的函数中执行,因此您的代码会变得更整洁)。然后,您可以在两个回合上进行循环,直到没有剩余的石头了。