javarestartterminate

Restarting program from a certain point after an if


I started studying Java not too long ago, I am currently trying to make a little game to see if I got the things I saw right. I want to make a "game" that let's you choose between two dialogue options which have different consequences. This is the code I used:

package programs;

import java.util.Scanner;

public class Programma1_0 {
public static void main(String[] args) {

    System.out.println(
            "You wake up in a laboratory. You don't remember ever being there. You actually don't remember anything.");
    System.out.println("A door opens, a girl comes towards you.");
    System.out.println("Girl:<<Hi, I see you woke up. How are you feeling?>>");
    System.out.println("(Write Good or Bad)");

    Scanner first = new Scanner(System.in);
    String firstch = first.nextLine();

    if (firstch.equals("Good")) {
        System.out.println("Great, we have a lot to explain.");
    } else if (firstch.equals("Bad")) {
        System.out.println("You should be alright in an hour or so. You've slept for a long time.");
    } else {
        System.out.println("(I told you to write Good or Bad)");

    }



    }
}

So far it's working as intended. The only problem is that if I write something other than Good or Bad i get the message "(I told you to write Good or Bad)" and the program terminates. Is there a way to automatically restart it? If i put more choices in, I want the program to automatically restart from the question where it terminated (So I don't play through half of the game, get a question wrong and have to restart the program from the start), is that possible? Thanks.


Solution

  • You can accomplish this by putting this before your if statement.

    while (true) {
         if (firstch.equals("Good") || firstch.equals("Bad")) 
             break;  
         else {
             System.out.println("(I told you to write Good or Bad)");
             firstch = first.nextLine();
         }
     }
    

    Then you can also remove the last else part of your if statement.

    Now it will continue asking for a new input till it gets either "Good" or "Bad"