如何在Java中重新启动程序?

huangapple go评论60阅读模式
英文:

How do I restart a program in Java?

问题

我已经查看了关于这个主题的其他StackOverflow问题,但作为一名新手开发者,我感到非常困惑。我正在尝试编写一个程序,向用户提问谜题,并在用户在一个特定的谜题上答错三次后重新启动。需要重新启动的代码是:

if (wrongAnswer == 3){
    System.out.println("你已经失败了三次。");
    restartApp();

我需要重新启动的代码应该放在当前restartApp()的位置。
提前感谢!

英文:

I have looked at other StackOverflow questions on this topic but being a new developer I am extremely confused. I am trying to write a program that asks the user riddles and restarts after the user gets three wrong answers on one specific riddle. The code that needs the restart is:

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

The code where I need to restart should go right where the restartApp() is right now.
Thanks in advance!

答案1

得分: 2

所以,正如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("输入一个值,输入-1退出..."); 

            int value = scan.nextInt();

            if(value == -1){
                System.out.println("正在退出");
                break;
            }else{
                System.out.println("对该值进行处理");
            }
        }
    } 
} 

以下是输出结果:

输入一个值,输入-1退出...
1
对该值进行处理
输入一个值,输入-1退出...
2
对该值进行处理
输入一个值,输入-1退出...
4
对该值进行处理
输入一个值,输入-1退出...
-1
正在退出
英文:

So, as Turing85 mentioned, restarting the whole program probably isn't the way to go. Generally, you use what's called a state machine. For this example, a simple one can be implemented with a while loop. Here's an example:

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");
			}
		}
	} 
} 

and here's the output:

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

huangapple
  • 本文由 发表于 2020年9月5日 02:00:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63746041.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定