Java: How to use a switch statement(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..
这篇关于Java:如何使用 switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java:如何使用 switch 语句


基础教程推荐
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01