在switchcase块中使用java
我有一个问题,关于如何在开关盒内进行几次检查?在案例2中,我需要做一些检查,但是添加第二个if块,我的应用程序什么都不做,只是挂起。我错在哪里了
BufferedReader inputCommand = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Instruction:");
System.out.println();
System.out.println("1 -- Show all product at the store");
System.out.println("2 -- Add the product at the client basket");
System.out.println("3 -- Show client basket");
System.out.println();
switch (inputCommand.readLine()) {
case "1":
basketCommand.get();
System.out.println();
break;
case "2":
System.out.println();
System.out.println("Select product to add into your basket");
if (inputCommand.readLine().equals("su")){
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
if (inputCommand.readLine().equals("an")){
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
break;
}
# 1 楼答案
您的第一个
if
语句占用了输入行,因此第二个if
语句没有任何内容可读只需在阅读一次后存储该行:
# 2 楼答案
每次执行
inputCommand.readLine()
时,程序都会等待您的输入。您不能像在本例中那样比较单个输入。最好的方法是将输入保存在变量中,然后执行检查。像这样的东西可以工作(未经测试):# 3 楼答案
在第二个case语句中,您应该只读取下一个输入一次:
# 4 楼答案
我假设这是一个用于学习目的的基本程序,所以我尽量保持简单
一,。别忘了关闭Scanner类
二,。始终将数字输入转换为小写(考虑“q”与“q”的情况)
三,。每次执行“scanner.nextLine()”时,您的程序都将停止并等待来自源的输入(在这种情况下,System.in配置为从键盘获取输入)
四,。系统出来println将在输入结束时将“\n”打印到屏幕上,导致它创建新行,您可以在字符串中使用此字符保存代码行
完整代码:
}
# 5 楼答案
用else if替换if