Java:如何使用 switch 语句

可能重复:
如何比较 Java 中的字符串?

我无法理解如何使用 Java switch 语句.在其中一个 case 语句中执行方法后,它仍然会转到默认语句并运行它.代码如下:

I am having trouble understanding how to use a Java switch statement. After executing a method in one of the case statements, it still then goes to the default statement and runs that too. Here's the code:

Scanner scanner = new Scanner(System.in);
String option = null;

while (option != "5") {
    ShowMenu();
    option = scanner.nextLine();
    switch (option) {
        case "1": ViewAllProducts(); break;
        case "2": ViewProductDetails(scanner); break;
        case "3": DeleteProduct(scanner); break;
        case "4": AddProduct(scanner); break;
        case "5": break;
        default: System.out.println("Invalid option. Please try again."); break;
    }
}

以上代码在main方法中.例如,在运行案例4"后,它会打印无效选项".

The above code is in the main method. After running case "4" for example, it prints "Invalid option."

推荐答案

我正在修改您的代码以在阅读新选项之前重新初始化您的扫描仪参考..

I am modifying your code to re-initialize your scanner reference before reading new option..

    Scanner scanner = new Scanner(System.in);
    String option = null;

    ShowMenu();
    option = scanner.nextLine();

    while (!"5".equals(option)) {
        switch (option) {
            case "1": ViewAllProducts(); break;
            case "2": ViewProductDetails(scanner); break;
            case "3": DeleteProduct(scanner); break;
            case "4": AddProduct(scanner); break;
            case "5": break;
            default: System.out.println("Invalid option. Please try again..."); break;
        }
        ShowMenu();
        scanner = new Scanner(System.in);  // Add this here

        option = scanner.nextLine();    // Use brand new scanner without any problem..
    }

休息,你可以从我提供的链接中阅读,了解读取用户输入的各种方法之间的区别..

Rest, you can read from the link I provided, to know the difference between various methods for reading user input..

相关文章