如果输入的输入不正确,如何重新启动switch语句

时间:2015-11-30 20:27:26

标签: java switch-statement

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


            }
}

1 个答案:

答案 0 :(得分:1)

像这样的问题的常见解决方案是将switch语句包装在do..while loop中。在循环结束时,如果你没有得到有效答案,你的循环就会重复,而它要做的第一件事就是重新打印你的菜单。它看起来像这样:

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