我正在学习 Java,并且正在关注一个模拟跳台滑雪比赛的项目。基本上他们想让我复制这个 Action :
The tournament begins!
Write "jump" to jump; otherwise you quit: jump
Round 1
//do something
Write "jump" to jump; otherwise you quit: jump
(continues)
我的问题只是关于如何循环这个问题。我知道我可以通过进入 while(true) 循环来做到这一点,如果用户输入等于“退出”,则立即中断。但是,我在多个地方读到这是一种不好的做法,而应该是: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");
}
如果我做这样的事情,即使命令是“退出”,它仍然会执行该循环的第一次迭代。如果我添加一个带有中断的 if,那么在 while 循环中设置条件就没有意义了。有更好的方法吗?我是否应该只使用 while(true) 循环,即使人们说这是不好的做法?
最佳答案
您可以尝试的另一件事是使用 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;
}
}
这不会打印“Round 1”。
因为您只能使用 if 语句。您可以尝试另一件事,那就是使用 continue
来自 Javadoc
The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop.
因此,在您询问用户输入后,您要么继续下一个循环,要么保持原样。这可以通过 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");
}
它有点像 break,但它不是完全退出循环,而是评估条件。
关于java - 如果我需要在开始时评估条件,有没有办法避免 while(true) ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57825284/