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

Java 如果输入了错误的输入,如何重新启动switch语句,java,switch-statement,Java,Switch Statement,解决此类问题的常见方法是将switch语句包装在一个文件中。在循环结束时,如果你没有得到一个有效的答案,你的循环会简单地重复,它要做的第一件事就是重新打印你的菜单。它看起来像这样: import java.util.Scanner; public class LibraryTester { public static void main(String args[]) { int userOption = Menu(sc); switch (userO

解决此类问题的常见方法是将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


            }
}

把它放在一个循环中…?您通常应该添加一个语言标记(一个例外是纯算法问题)。我已经为您添加了
Java
标记。我不明白您为什么要重新启动switch语句,它会再次出现在同一个case块中并不断重复。很可能您希望switch语句之前的代码也重复,不是吗?对不起,伙计们,我才刚刚开始学习Java或任何编程。如果用户没有输入正确的选项/案例,我需要创建的菜单再次出现在扫描仪中
bool needAnswer = true;
do {
    int userOption = Menu(sc);
    ... // set needAnswer=false if you're happy with their result.
} while (needAnswer);