Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go back to a specific line in Java?

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?

like image 580
KTF Avatar asked Jan 13 '23 11:01

KTF


1 Answers

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;
    }
}
like image 160
Sergey Kalinichenko Avatar answered Jan 18 '23 16:01

Sergey Kalinichenko