【发布时间】:2011-09-16 21:24:34
【问题描述】:
我试图弄清楚为什么我的程序重复打印相同的语句。当我输入好的值时,我可以让这个方法正常工作,但是我设置了一个 else 语句来捕获无效的选择。当我的 else 语句运行时,它会无限打印并且 while 循环永远不会开始。我想不通。我将粘贴整个方法,但将问题区域加粗。我希望这很清楚。
public static int[][] placeCheese(int [][] gameBoard, String Player1Name)
{
Scanner console = new Scanner(System.in);
int turnTaker = 0;
int validRow = 0;
int validCol = 0;
int RowIndex = -1;
int ColIndex = -1;
while(turnTaker == 0)
{
while(validRow == 0)
{
System.out.println( Player1Name + ", please place your cheese by choosing a row, or choose -1 to exit.");
RowIndex = console.nextInt() -1;
if(RowIndex < gameBoard.length && RowIndex >=0)
{
validRow++;
}
else if(RowIndex == -2)
{
System.out.println("Thanks for playing, " + Player1Name + " has forfeited!");
System.exit(0);
}
}
while(validCol == 0){
System.out.println( Player1Name + ", please place your cheese by choosing a column, or choose -1 to exit.");
ColIndex = console.nextInt() -1;
if(ColIndex < gameBoard.length && ColIndex >=0)
{
validCol++;
}
else if(RowIndex == -2)
{
System.out.println("Thanks for playing, " + Player1Name + " has forfeited!");
System.exit(0);
}
}
if(gameBoard[RowIndex][ColIndex] == 0)
{
gameBoard[RowIndex][ColIndex] = 1;
turnTaker++;
numPieces1--;
}
else
{
System.out.println("this space is already occupied, please choose again.");
}
return gameBoard;
}
【问题讨论】:
-
请尝试将代码格式化为更易读的内容..
-
哎呀,我正在编辑这个,它不允许我保存它。
-
如果进入无限循环进行调试,您会看到什么?该工具可能会帮助您解决问题,因为这就是它的用途。
-
不是所有的代码路径都会改变
turnTaker的值(例如:else块),因此是无限循环。 -
我不知道我是否不清楚问题所在。我希望整个方法重复迭代,直到将 turntaker 设置为 = 1。这只会在放置作品时发生。现在它卡在 else 语句中,并且永远不会要求玩家再试一次。如果他们到达 else 语句并改变了turntaker,该方法不会再次尝试让他们放置一块,对吧?
标签: java loops while-loop infinite