问题描述
我已经查看了有关此主题的其他StackOverflow问题,但是作为一名新开发人员,我感到非常困惑。我正在尝试编写一个程序,询问用户谜语,并在用户在一个特定谜语上得到三个错误答案后重新启动。需要重启的代码是:
if (wrongAnswer == 3){
System.out.println("You have Failed three times.");
restartApp();
我需要重新启动的代码应该在正确的restartApp()位置。 预先感谢!
解决方法
因此,正如Turing85提到的那样,重启整个程序可能不是走的路。通常,您使用所谓的state machine。对于此示例,可以使用while循环实现一个简单的示例。这是一个示例:
import java.util.Scanner;
public class foo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
boolean running = true;
while(running){
System.out.println("enter a value,enter -1 to exit...");
int value = scan.nextInt();
if(value == -1){
System.out.println("exiting");
break;
}else{
System.out.println("do stuff with the value");
}
}
}
}
这是输出:
enter a value,enter -1 to exit...
1
do stuff with the value
enter a value,enter -1 to exit...
2
do stuff with the value
enter a value,enter -1 to exit...
4
do stuff with the value
enter a value,enter -1 to exit...
-1
exiting