0

我已经查看了有关此主题的其他 StackOverflow 问题,但作为一名新开发人员,我非常困惑。我正在尝试编写一个程序,询问用户谜语并在用户在一个特定谜语上得到三个错误答案后重新启动。需要重启的代码是:

if (wrongAnswer == 3){
                        System.out.println("You have failed three times.");
                        restartApp();

我需要重新启动的代码应该在 restartApp() 现在所在的位置。提前致谢!

4

1 回答 1

2

因此,正如 Turing85 所提到的,重新启动整个程序可能不是要走的路。通常,您使用所谓的状态机。对于此示例,可以使用 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
于 2020-09-04T18:25:37.793 回答