4

I'm writing code that involves an if-else statement asking the user if they want to continue. I have no idea how to do this in Java. Is there like a label I can use for this?

This is kind of what I'm looking for:

--label of some sort--
System.out.println("Do you want to continue? Y/N");
if (answer=='Y')
{
    goto suchandsuch;
}
else
{
    System.out.println("Goodbye!");
}

Can anybody help?

KTF
  • 317
  • 3
  • 7
  • 13
  • call suchandsuch method. if the condition is true. – newuser Sep 04 '13 at 01:45
  • Please go thorough these posts: 1) http://stackoverflow.com/questions/2430782/alternative-to-goto-statement-in-java 2) http://stackoverflow.com/questions/2545103/is-there-a-goto-statement-in-java – aces. Sep 04 '13 at 01:46
  • 1
    I would use a while loop and break unless the user decides to continue. It is very unusual to use goto for any programming these days as most loop constructs and/or function-based programming are better for each specific situation a goto might be used in. – abiessu Sep 04 '13 at 01:47
  • `goto` has its place (though its place is fairly limited). Obviously, its place doesn't include languages that don't support it :-) – paxdiablo Sep 04 '13 at 01:49

1 Answers1

9

Java has no goto statement (although the goto keyword is among the reserved words). The only way in Java to go back in code is using loops. When you wish to exit the loop, use break; to go back to the loop's header, use continue.

while (true) {
    // Do something useful here...
    ...
    System.out.println("Do you want to continue? Y/N");
    // Get input here.
    if (answer=='Y') {
        continue;
    } else {
       System.out.println("Goodbye!");
       break;
    }
}
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523