如果在while循环内,则不能突破while循环

Ven*_*nto 3 java loops if-statement break while-loop

我最近开始学习Java并在测试时发现了一个问题.这可能是一个非常简单的问题,但我似乎无法解决它.这是我的代码:

    int firstj = 1;

    if (firstj == 1) {
        String choice = "Type a number between 1 and 4";
        System.out.println(choice);
        while (true) {

            if (firstj == 1) {
                Scanner third = new Scanner(System.in);
                String thirdch = third.nextLine();

                while (true) {

                    if (thirdch.equals("1")) {
                        System.out.println("Show choice and accept input again ");
                        System.out.println(choice);
                        break;
                    } else if (thirdch.equals("2")) {
                        System.out.println("Show choice and accept input again ");
                        System.out.println(choice);
                        break;
                    } else if (thirdch.equals("3")) {
                        System.out.println("Show choice and accept input again ");
                        System.out.println(choice);
                        break;
                    }

                    else if (thirdch.equals("4")) {
                        // I need this to break the loop and move on to the
                        // "Done." string
                        break;
                    }

                    else {
                        System.out.println("Type a number between 1 and 4");
                        thirdch = third.nextLine();
                    }
                }

            }
        }
    }
    String done = "Done";
    System.out.println(done);
Run Code Online (Sandbox Code Playgroud)

我想这样做,当你输入1,2或3时,你得到的字符串告诉你再次输入一个数字并接受用户输入,而当你输入4时,循环中断并转到完成字符串.如果你能用一个简单的代码帮助我解决这个问题,我将不胜感激,因为我不知道任何更高级的东西.

And*_*ner 7

您可以标记循环,然后在break语句中使用标签来指定要打破的循环,例如

outer: while (true) {
  while (true) {
    break outer;
  }
}
Run Code Online (Sandbox Code Playgroud)


Bat*_*eba 5

打破嵌套循环的最可扩展方法是将整个事物放在函数中并使用return.

在Java中打破标签是另一种选择,但它可能会使代码变得脆弱:你可能会受到一些顽固的重构者的摆布,他们可能会感到倾向于将"破坏标签"移动到幸福地意识不到后果; 编译器无法警告这样的恶作剧.