java - 如果在 while 循环内,则无法跳出 while 循环

标签 java loops if-statement while-loop break

我最近开始学习 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);

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

最佳答案

您可以标记循环,然后在 break 语句中使用该标签来指定要跳出哪个循环,例如

outer: while (true) {
  while (true) {
    break outer;
  }
}

关于java - 如果在 while 循环内,则无法跳出 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32869552/

相关文章:

java - 如何在 Java 中进行循环?

java - 如何迭代对象数组[Gson反序列化]?

Javascript if else 定时器在特定日期

python - 在 Python 的 If 语句中使用 boolean 值

java - IntelliJ IDEA Gradle + Groovy

java - 带有 tomcat 服务器的自签名证书的 TLS - 无法加载 PEM 客户端证书

r - 我在 r 中的 for 循环在第一次迭代时停止

C++ If语句逻辑

java - 某个词被提及的次数

java - 正则表达式匹配 Java 中的未转义逗号