【问题标题】:While loop getting stuck in infinite loop虽然循环陷入无限循环
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

  • 我刚刚注意到了同样的事情。谢谢!
  • 哦抱歉不知道怎么做,会想办法的:)
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    你没有改变 turnTaker 的值,所以它总是保持为零。

    【讨论】:

    • 哦,哎呀!我在编辑之前发布了这个,现在我看到了其余的代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多