Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 756
AntonioK Avatar asked Nov 13 '14 03:11

AntonioK


People also ask

What does \t and \n Do Java?

\t Insert a tab in the text at this point. \b Insert a backspace in the text at this point. \n Insert a newline in the text at this point.

Is there a goto in Java?

Unlike C++, Java does not support the goto statement. Instead, it has label . Labels are used to change the flow of the program and jump to a specific instruction or label based on a condition.

How do you call a line in Java?

To call a method in Java, write the method's name followed by two parentheses () and a semicolon; The process of method calling is simple.


Video Answer


2 Answers

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.

like image 75
Matt Walston Avatar answered Nov 15 '22 00:11

Matt Walston


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);
like image 32
tckmn Avatar answered Nov 15 '22 00:11

tckmn