【问题标题】:Restart while loop if boolean == false如果 boolean == false 则重新启动 while 循环
【发布时间】:2018-11-05 16:12:11
【问题描述】:

我正在尝试通过制作数独谜题来提高 Java 水平,但是我遇到了一些问题。就目前而言,如果我在数独中输入任何“非法”输入,它只会继续,但如果它是“非法”,我试图让脚本再次请求一个值。如下代码所示,当我的公共布尔“移动”为假时,我试图再次启动 while 循环。

public static void main(String[] args) throws Exception  {
    Sudoku s = new Sudoku("C:\\Users\\caspe\\Downloads\\Sudoku001.sdk");
    s.printBoard();
    s.errorCheck();
    s.getNum();

    while(getNum() > 0) {
        System.out.println("Next move, please (row , column , value )");
        Scanner scanner = new Scanner(System.in);
        int row = scanner.nextInt();
        int column = scanner.nextInt() ;
        int value = scanner.nextInt();
        if (s.moves(row, column, value) == false); {
            //Try again
        }

        s.printBoard();
    }
}

经过几次不同的尝试,我仍然无法找到解决方案,非常感谢您的帮助!

这是我进一步理解的getNum方法:

public static int getNum() {
    int getNumb = 0;
    for(int j = 0; j < list.size(); j++) {
        for (int i=0; i < list.get(j).length(); i++) {
            if(list.get(i).charAt(j) == '.') {
                getNumb++;
            }
        }
    }
    return getNumb;
}

【问题讨论】:

  • 能分享一下getNum方法吗?它有什么作用?
  • 您可以使用 continue 再次重做循环。
  • Restarting the while loop的可能重复
  • 如果我只使用 continue,我的“printBoard”将无法访问
  • 什么是list 变量?您在该列表中存储什么样的对象?

标签: java while-loop boolean


【解决方案1】:

您编写代码的方式将打印数独板,无论 s.move 是真还是假。解决这个问题的方法是在 if 语句中添加 else 语句。

例如:

if(s.moves(row, column, value) == false){
    //print error message
}else {
    s.printBoard();
}

【讨论】:

  • 我本可以发誓我尝试过那个解决方案。不过谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多