【发布时间】:2019-12-13 19:08:57
【问题描述】:
这是我在这里的第一个疑问,我对此真的很菜鸟,而且我的英语不是最好的,所以首先抱歉,如果有一个假人错误。 问题是我想做一个 for 循环来保存来自控制台的每个用户输入并将其添加到名为“Order”的列表中。如果用户正确键入了订单,则必须执行此操作,并且必须检查该订单是否存在于菜单上。如果不是,我们必须让用户知道情况并询问他/她是否想要我们在菜单上提供的东西。此外,在列表中保存的每个输入之后,我们想询问用户他/她是否想订购更多东西,所以如果是,则必须初始化循环,如果不是,我们必须退出循环。 我的代码的问题是,无论我在控制台中输入什么,循环都是从头到尾完成每个 cicle。 错误在哪里? 谢谢!!!
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Fase2_final {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] menu = { "chicken", "steak", "hamburger", "spaghettis", "pizza" };
int[] price = { 10, 15, 20, 5, 12 };
boolean order = true;
for (int i = 0; i < menu.length; i++) {
System.out.println("We have " + menu[i] + " for " + price[i] + "€");
}
int yes = 1;
int no = 0;
Scanner yesOrNo = new Scanner(System.in);
System.out.println("What do you want to eat?");
List<String> Order = new ArrayList<String>();
do {
Scanner inputOrder = new Scanner(System.in);
String userOrder = inputOrder.next().toLowerCase();
for (int j = 0; j < menu.length; j++) {
if (userOrder.equals(menu[j])) {
Order.add(userOrder);
System.out.println("You ordered" + Order + "\nSomething more?" + "\nSay YES with 1 and NO with 0");
} else if (userOrder.equals(menu[j]) == false) {
System.out.println("We don't have this on menu!"
+ "\nDo you want to order another thing that we do have in menu?" + "\nSay YES with 1 and NO with 0");
} else if (yesOrNo.nextInt() == no) {
System.out.println("Order finished!");
}
}
} while (yesOrNo.nextInt() == yes);
}
}```
【问题讨论】:
-
提示:每个
nextInt()调用都会返回单独的值,这就是为什么我们不直接将它放在条件中而是将值存储在变量中并在条件中使用该变量。 -
Hint2:不要使用许多扫描仪来读取同一资源。这使得事情变得复杂,因为扫描仪读取了整个可用数据,因此即使用户将提供像
1 2 3[enterKey]这样的数据,nextInt()也会返回1但2 3也会被该扫描仪读取,从而阻止其他扫描仪读取它们。跨度> -
好的,那么我将更换两台扫描仪并只使用一个名为
sc的扫描仪来检查输入,但我可以用什么来代替nextInt()?我需要知道用户是否输入“是”或“否”才能知道程序必须做什么。