我正在编写一个程序,允许用户使用switch语句从菜单中选择项目,但是当选择多个项目时,我会得到一个例外。我目前的代码如下。
System.out.println("Transaction 1");
System.out.println();
System.out.println("Menu");
System.out.println();
System.out.println("(1) Hamburger $1.99\n(2) Cheeseburger $2.29\n(3) Chicken Wrap $3.39\n(4) Chicken Nuggets $2.29\n(5) Lrg French Fries $2.49\n(6) Sml French Fries $1.79\n(7) Bottled Water $2.19\n(8) Lrg Soda $1.89\n(9) Sml Soda $1.49");
System.out.print("\nPlease type the numbers that correspond to the food you would like to order separated by commas: ");
toneorder = userInput.nextInt();
switch (toneorder) {
case 1:
tonefood = "Hamburger";
break;
case 2:
tonefood = "Cheeseburger";
break;
case 3:
tonefood = "Chicken Wrap";
break;
case 4:
tonefood = "Chicken Nuggets";
break;
case 5:
tonefood = "Lrg French Fries";
break;
case 6:
tonefood = "Sml French Fries";
break;
case 7:
tonefood = "Bottled Water";
break;
case 8:
tonefood = "Lrg Soda";
break;
case 9:
tonefood = "Sml Soda";
break;
}
答案 0 :(得分:1)
你需要将整个事情从获取输入,直到switch语句的结尾,抛到循环中。
System.out.print("\nPlease type the numbers that correspond to the food you would like to order separated by spaces: ");
do{
toneorder = userInput.nextInt();
switch (toneorder) {
case 1: tonefood = "Hamburger";
break;
case 2: tonefood = "Cheeseburger";
break;
case 3: tonefood = "Chicken Wrap";
break;
case 4: tonefood = "Chicken Nuggets";
break;
case 5: tonefood = "Lrg French Fries";
break;
case 6: tonefood = "Sml French Fries";
break;
case 7: tonefood = "Bottled Water";
break;
case 8: tonefood = "Lrg Soda";
break;
case 9: tonefood = "Sml Soda";
break;
}while (userInput.hasNextInt());
如果您想将所有选定的选项存储在变量'tonefood'中,您还需要将tonefood = /*item*/
更改为tonefood += /*item*/ + " ";
。
另外,不要提示用户用逗号分隔输入。将它们用空格分隔以自动获取下一个数字,因为逗号不能存储在int变量中。所以说你要输入数字1,2和3.输入应该是1 2 3
而不是1, 2, 3
或1,2,3
。
用户需要在输入后输入非整数值才能终止输入。如果您想要提示用户,可以使用1 2 3 buy
或checkout
之类的内容。
希望这有帮助!