JC1
JC1

Reputation: 15

How can you start a switch statement over again if an incorrect input is entered

import java.util.Scanner;

public class LibraryTester {

    public static void main(String args[]) {

        int userOption = Menu(sc);
        switch (userOption){
        case 1:
            System.out.println("Please enter Book ID"); break;
        case 2:
            System.out.println("Please enter Book details"); break;
        case 3:
            System.out.println("Please enter the first word of the book you wish to delete"); break;


        default: System.out.println("Please enter a number between 1-6"); break;
// i'm not sure how to print the menu again


        public static int Menu(Scanner sc) {
        System.out.println("Please choose a number from the following options");
        System.out.println("1. Add a Book");
        System.out.println("2. Edit a Books details");
        System.out.println("3. Delete a Book");
        System.out.println("4. Loan a Book");
        System.out.println("5. Return a Book");
        System.out.println("6. Exit the program");
        int userOption = sc.nextInt();
        sc.nextLine();
        return userOption;

//this is only a small part of my code


            }
}

Upvotes: 2

Views: 3719

Answers (1)

Scott Stafford
Scott Stafford

Reputation: 44798

The common solution to a problem like this is to wrap the switch statement in a do..while loop. At the end of the loop, if you haven't gotten a valid answer, your loop would simply repeat, and the first thing it would do is to reprint your menu. It would look something like this:

bool needAnswer = true;
do {
    int userOption = Menu(sc);
    ... // set needAnswer=false if you're happy with their result.
} while (needAnswer);

Upvotes: 1

Related Questions