有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如果输入了错误的输入,如何重新启动switch语句

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) 个答案

  1. # 1 楼答案

    解决此类问题的常见方法是将switch语句包装在^{} loop中。在循环结束时,如果你没有得到一个有效的答案,你的循环会简单地重复,它会做的第一件事是重新打印你的菜单。它看起来像这样:

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