redeclare scanner java while loop menu option code example

Example 1: how to make a java main menu loop after using a case

do{
  //Menu options
  System.out.print("6.) Exit\n");
  System.out.print("\nEnter Your Menu Choice: ");

  choice = input.nextInt();

  switch(choice){
        //Your cases from 1 to 6.
        default:
            System.out.println("Invalid menu choice; try again.");
            break;
   }
}while(choice != 6);

Example 2: How to make a Java Main Menu Loop after using a case

int choiceentry;

do {
    System.out.println("Enter \"1\", \"2\" or \"3\"");
    choiceentry = scanchoice.nextInt();

    switch (choiceentry)
    {
        case 1:
            // do something
            break;
        case 2: 
            // ..something else
            break;
        case 3: 
            // .. exit program
            break;
        default:
            System.out.println("Choice must be a value between 1 and 3.");
    }   
} while (choiceentry != 3);

Tags:

Java Example