-1

I'm trying to write an program that let's you choose between two things. But after executing the option that I chose, I want to be able to return the the beginning of that same option.

switch (option) {
case 1:
    System.out.println("Start of option 1");
    //option 1 will do things here
    System.out.println("End of option 1");
    //I want to return at the beginning of this case at the end of it
    break;

case 2:
    System.out.println("Start of option 2");
    //option 2 will do things here
    System.out.println("End of option 2");
    //I want to return at the beginning of this case at the end of it
    break;

default:
    break;
}

An option to get out of the selected case too. Also, would it be easier to implement what I'm trying to do with the use of if-statements instead?

1 Answers1

0
case 2:
    case2sub();
default:
    break;
}
}

public static void case2sub() {
    System.out.println("Start of option 2");
    //option 2 will do things here
    System.out.println("End of option 2");
    //I want to return at the beginning of this case at the end of it
    boolean end = false;
    System.out.println("QUIT? (Y/N)");
    keyboardInput =  new Scanner(System.in).nextLine();
    if (keyboardInput.equalsIgnoreCase("Y"))
            end = true;
    else{}
    if (end){}
    else
        case2sub();
}

If you put your cases in their own methods, you can call them recursively until you put in an exit statement. Recursion works and so does a while loop.

public static void case2sub() {
    boolean end = false;
    while (!end)
    {
    end = false;
    System.out.println("Start of option 2");
    //option 2 will do things here
    System.out.println("End of option 2");
    //I want to return at the beginning of this case at the end of it
    System.out.println("QUIT? (Y/N)");
    keyboardInput =  new Scanner(System.in).nextLine();
    if (keyboardInput.equalsIgnoreCase("Y"))
        end = true;
    }
}

You can exit this any number of ways. These are just two answers.

DarkJade
  • 270
  • 1
  • 8