如果我需要一开始就评估条件,是否有一种方法可以避免while(true)?

leo*_*rdo 5 java while-loop

我正在学习Java,并且正在关注一个模拟跳台滑雪比赛的项目。基本上,他们希望我复制此操作:

The tournament begins!

Write "jump" to jump; otherwise you quit: jump

Round 1

//do something

Write "jump" to jump; otherwise you quit: jump
(continues)
Run Code Online (Sandbox Code Playgroud)

我的问题仅仅是在循环这种方式。我知道我可以通过进入while(true)循环来做到这一点,如果用户输入等于“ quit”,则立即中断。但是,我在多个地方都读到这是一个不好的做法,而应该是:while(condition)。如果要这样做,则直到完成第一次迭代后,循环才会中断。说:

String command = "placeholder";
while (!command.equals("quit")) {
    System.out.println("Write \"jump\" to jump; otherwise you quit: ");
    command = input.nextLine();
    System.out.println("\nRound 1");

    }
Run Code Online (Sandbox Code Playgroud)

如果我做这样的事情,即使命令是“退出”,它仍然会执行该循环的第一次迭代。而且,如果我添加带有中断的if,则在while循环上没有条件是没有意义的。有更好的方法吗?即使人们说这是不好的做法,我也应该只使用while(true)循环吗?

Goi*_*ion 1

您可以尝试的另一件事是使用 switch 语句。我不知道你有多少条件,所以可能不可行。这是代码。

Scanner input = new Scanner(System.in);
String command = "placeholder"; // magic at this line
while (!command.equals("quit")) {
    System.out.print("Write \"jump\" to jump; otherwise you quit: ");
    command = input.nextLine();
    switch (command) {
    case "jump":
        System.out.println("\nRound 1");
        break;
    case "quit":
        break;
    default:
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

这不会打印“Round 1”。

因为您仅限于 if 语句。您还可以尝试另一件事,那就是使用continue

来自 Javadoc

continue 语句跳过 for、while 或 do-while 循环的当前迭代。未标记的形式跳到最内层循环体的末尾,并计算控制循环的布尔表达式。

因此,在您询问用户输入后,您要么继续下一个循环,要么保持不变。这可以通过 if 语句来完成。这是代码。

Scanner input = new Scanner(System.in);
String command = "placeholder"; // magic at this line
while (!command.equals("quit")) {
    System.out.println("Write \"jump\" to jump; otherwise you quit: ");
    command = input.nextLine();
    if (command.equals("quit"))
        continue;
    System.out.println("\nRound 1");
}
Run Code Online (Sandbox Code Playgroud)

它有点像break,但它不是完全退出循环,而是评估条件。

  • @leonardo 请考虑通过单击该复选标记来接受最能解决您问题的答案! (2认同)