AntonioK
AntonioK

Reputation: 107

How do you go back to a specific line in Java?

I am trying to make a Math Calculator Application. However I am wondering if there is a statement that allows you to go back to a certain line?

Let me clarify:

I am not referring to a loop. Here's a possibly scenerio: Let's say that the user has run the program and reached let's say line 54. If I have an if-else statement there, if there a way that I could make it so that "if (input = 0){go back to line 23}

Is there anything that may allow me to do this, not including a loop?

Upvotes: 5

Views: 6410

Answers (3)

Matt Walston
Matt Walston

Reputation: 119

Java does not have a goto (goto is a reserved word but not used). Consider how your approach and language choice fit together. There is likely a better way to do this. Consider extracting a method or using a flag inside of a loop. Without more information, guidance will be limited.

Upvotes: 4

tckmn
tckmn

Reputation: 59363

Nope.

The goto statement exists in C and C++, which Java is vaguely similar to, but it's generally considered very bad practice to use. It makes code difficult to read and debug. Here are some correct ways to solve this problem with more structured programming:

do {
    ...
} while (input == 0);
private void doTheThing() { // please use a better name!
    ...
    if (input == 0) doTheThing(); // recursion not recommended; see alternate
                                  // method below
}

// alternate method:
do {
    doTheThing();
} while (input == 0);

Upvotes: 2

RJGordon
RJGordon

Reputation: 11

Why can't you use a loop?

Put your code in a function, then put in a loop that runs while input = 0.

Upvotes: 1

Related Questions