Java 一个switch语句可以输入多个数字吗?
我正在编写一个程序,允许用户使用switch语句从菜单中选择项目,但是当选择多个项目时,我会得到一个异常。我现在的代码如下Java 一个switch语句可以输入多个数字吗?,java,Java,我正在编写一个程序,允许用户使用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) Che
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;
}
您需要将从获取输入到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=/*item*/
更改为tonefood+=/*item*/+”代码>如果要将所有选定选项存储在变量“tonefood”中
另外,不要提示用户用逗号分隔输入。将它们用空格分隔以自动获取下一个数字,因为逗号不能存储在int变量中。假设你想输入数字1、2和3。输入应该是1 2 3
,而不是1,2,3
或1,2,3
用户需要在输入后输入一个非整数值来终止输入。如果您希望提示用户购买,则类似于123buy
或checkout
的功能将起作用
希望这有帮助 “多个项目”是指用户键入了,例如“12”或“12”吗?您需要解析他们的输入(例如,在空格字符上拆分)或类似内容。您会遇到什么类型的异常?此外,根据给出的代码,我们是否假设用户只会被提示输入订单一次,而您却多次收到订单错误?我注意到您将我的答案取消标记为解决方案@jdoe12345。请评论它为什么不起作用,我会相应地修复它。错误来自于他们订购多件东西时,即如果我为我想要订购的东西键入“1,3,5”,我会得到输入不匹配异常,而不是输出为“汉堡包,鸡肉包,Lrg炸薯条”然而,如果我只订购了一件它输出正确的东西,那是意料之中的。输入应该是“1 3 5”而不是“1,3,5”,因为这将尝试在int变量中存储逗号,这是无法完成的@jdoe12345