1

我试图弄清楚为什么我的程序重复打印相同的语句。当我输入好的值时,我可以让这个方法正常工作,但是我设置了一个 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;
}
4

3 回答 3

2

第一次调用时,它将强制您提供有效的列号和行号;正方形将被设置,turnTaker将增加,循环将终止。

第二次调用时,如果选择的行号和列号相同,则turnTaker不会增加,因为数组中选择的点不为 0。因为andvalidRowvalidCol为 0,而且它永远不会要求你更多数字——它将进入一个无限循环打印消息而不再提示!

打印消息的“else”子句可以通过将validRowandvalidCol再次设置为 0 来解决此问题。turnTaker正如其他人指出的那样,如果这些变量也是布尔值而不是整数,那会更好。

于 2011-09-16T21:36:55.477 回答
1

您的代码难以辨认,但如果我不得不猜测,我会说您没有在 else 语句中更改 turnTaker。无限循环!

于 2011-09-16T21:28:27.610 回答
0

您不会更改 turnTaker 的值,因此它将始终保持为零。

于 2011-09-16T21:27:08.853 回答