Java:如何使用switch语句 [英] Java: How to use a switch statement
问题描述
可能重复:
如何比较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..
这篇关于Java:如何使用switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!