gpt4 book ai didi

java - 一些 if 在 switch-case block 中

转载 作者:行者123 更新时间:2023-12-04 05:37:13 25 4
gpt4 key购买 nike

我对如何在 switch-case 中执行多项检查有疑问?我需要在案例 2 中做一些检查,但是添加第二个 if block ,我的应用程序什么都不做,它只是挂起。我做错了什么?

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;
}

最佳答案

在第二个 case 语句中,您应该只读取下一个输入一次:

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");

String next = inputCommand.readLine();
if (next.equals("su")) {
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
else if (next.equals("an")) {
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
break;
}
}

关于java - 一些 if 在 switch-case block 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51838955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com