Juan Alvarez
Juan Alvarez

Reputation: 29

how to return to certain part of the program? java

I have a program that its supposed to display a menu take a number from the user to select from the menu do what its supposed to do and then return to the menu and I don't know how can I return to the menu?

Here is my code:

public class tst {
    public static void main (String [] args){
        Scanner reader = new Scanner(System.in);
        System.out.println("Select");
        int slct = reader.nextInt();
        System.out.println("1.optionone");
        System.out.println("2.optiontwo");
        System.out.println("1.optionthree");
        switch (slct){
            case 1:System.out.println("you have selected optionone");// and then its suposed to go back to the menu
            case 2:System.out.println("you have selected optiontwo");// and then its suposed to go back to the menu
            case 3:System.out.println("you have selected optionthree");// and then its suposed to go back to the menu
        }        
    }        
}

the question its How can i make so after it print you have selected x option i returns to the menu again?

Upvotes: 2

Views: 689

Answers (2)

Arc676
Arc676

Reputation: 4465

Use a while loop. This allows you to loop back to the beginning of your loop after reaching the end.

EDIT: Java has no goto statement. However, if you ever decide to learn a new language (such as C) that does have goto, don't use it.

Whatever you do, don't use goto. It's goto is considered extremely bad practice and has become subject to absurd humor.

Example:

boolean keepGoing = true;
while (keepGoing){
    //print out the options
    int slct = reader.nextInt(); //get input
    switch(slct){
        case 1:
            //user inputted 1
            break; //otherwise you will fall through to the other cases
        case 2:
            //...
            break;
        case 3:
            //...
            break;
        case 4: //or other number to quit, otherwise this will repeat forever
            keepGoing = false; //stop the loop from repeating again
            break;
    }
}

Upvotes: 3

Shiladittya Chakraborty
Shiladittya Chakraborty

Reputation: 4418

In your case you can take design your menu using do while loop. You can re design your menu look like :

int slct = 0;

do {
  System.out.println("1.optionone");
  System.out.println("2.optiontwo");
  System.out.println("3.optionthree");
  System.out.println("4.Quit");
  Scanner reader = new Scanner(System.in);
  System.out.println("Select");
  slct = reader.nextInt(); //get input

  switch(slct){
  case 1:
    //user inputted 1
    break; //otherwise you will fall through to the other cases
  case 2:
    //...
    break;
  case 3:
    //...
    break;
  }


} while(slct != 4);

When user enter 4 option then it will break the loop. Means do while loop will break using 4 input.

Upvotes: 1

Related Questions