0

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!

  • What is is that you want to restart? Could you put the logic in a loop? – Sam Orozco Sep 04 '20 at 18:02
  • 5
    I would suggest to reset the state of the application instead of restarting the whole application. – Turing85 Sep 04 '20 at 18:02
  • Welcome to Stack Overflow. Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Then [edit] your question to include the source code you have as a [mcve], which can be compiled and tested by others. Also check the [help/on-topic] to see what questions you can ask. Please show your attempts you have tried and the problem/error messages you get from your attempts. – Progman Sep 04 '20 at 18:08
  • If you are confused about this I would suggest you read a book / try a tutorial online in order to learn how it works. See for example [Java docs](https://docs.oracle.com/javase/tutorial/getStarted/index.html) – darclander Sep 04 '20 at 18:16

1 Answers1

2

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
Warlax56
  • 1,170
  • 5
  • 30