Search code examples
javac++goto

Jumping to lines in Java


I have just now started learning Java and one of the differences I noticed from C++ and VB is that Java has no goto statements, which I tend to use a lot while programming.

Is there any way I could jump between lines using another statement? I tried to use break and continue but to no avail (I might be doing something wrong).

Here is the code with goto statements and how I want it to operate:

public class HelloWorld {

static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
    jump1:
    System.out.print("What do you want to calculate? ");
    String method = sc.nextLine();
    if (method.equals("tax")) tax();
    else {
        System.out.print("Please input a valid method. \n\n");
        goto jump1;
    }  
}

What is a good replacement for the goto commands?


Solution

  • You should avoid "goto" statements in all languages, according to the rules of "structured programming", instead using if-then-else or do or while or for loops to control program flow.

    Java DOES have a sort of "goto" statement that you COULD use to only slightly modify your code, but consider the while loop below and the break statement, which jumps out of the loop.

      public static void main(String[] args) {
        String method = "";
        while(! method.equals("tax")){
          System.out.print("What do you want to calculate? ");
          method = sc.nextLine();
          if(method.equals("tax"))
            break;
          System.out.print("Please input a valid method. \n\n");
        }
        tax();
      }
    

    The break statement enables your "Please ... valid" statement to display. You could also use this:

      public static void main(String[] args) {
        String method = "";
        while(! method.equals("tax")){
          System.out.print("What do you want to calculate? ");
          method = sc.nextLine();
        }
        tax();
      }
    

    I also kind of like this:

      public static void main(String[] args) {
        String method = "";
        while(1==1){
          System.out.print("What do you want to calculate? ");
          method = sc.nextLine();
          if(method.equals("tax")
            break;
          System.out.print("Please input a valid method. \n\n");
        }
        tax();
      }
    

    You might go to the Java tutorials; they're good.