Koragan
Koragan

Reputation: 31

How to jump back to beginning of an if statement if user inputs wrong answer

Here is the code:

if (g1 == 6) {
   System.out.println("Correct! Proceed to the next challenge");
} 
else {  
   System.out.println("That is incorrect, please try again");
}

How do I allow them to try again if, for example they input "4" for their guess? Basically, how do I go back to the beginning of the if statement?

Upvotes: 3

Views: 8156

Answers (2)

Richard Sitze
Richard Sitze

Reputation: 8463

This is what while loops are designed for.

In learning to program focus on thinking about the sequence of instructions through if and while constructs. If you get a suggestion that gives you some details, read it. Understand it.

Think about what it's doing, what you want it to do - and how you might bridge that gap.

If you're asking why something is "spamming", your thoughts should turn toward what else needs to be going on inside the loop that's causing the spam.

Upvotes: 3

Nickoli Roussakov
Nickoli Roussakov

Reputation: 3409

String g1 = "";
try {
    InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
    do {
      g1 = in.readLine();
      if (g1 == 6) {
        System.out.println("Correct! Proceed to the next challenge");
      } else {
        System.out.println("That is incorrect, please try again");
      }
    } while(g1 != 6);
} catch (Exception e) {
System.out.println("Error! Exception: "+e); 
}

Upvotes: 4

Related Questions