整个代码几乎像我想要的那样工作,但是我不知道如何在不完成整个for循环的情况下让用户知道错误,因此它将重复错误直到循环结束,并且重复错误直到错误结束找到正确的答案。如果我不使用for循环,我将不知道如何在menu []中进行迭代以搜索其中的元素与用户输入之间的每一个匹配项...如果我在控制台“ pizza”中编写用户输入内容,返回:
We have chicken for 10€
We have steak for 15€
We have hamburger for 20€
We have spaghettis for 5€
We have pizza for 12€
What do you want to eat?
pizza
Sorry, we don't have that
Sorry, we don't have that
Sorry, we don't have that
Sorry, we don't have that
You ordered pizza
Want something more? Say YES with 1 and NO with 0
我只想退回我订购的东西,当我写错东西时,我只想一个建议而不是五个!对不起,我的英语和代码知识差!谢谢!
String[] menu = { "chicken", "steak", "hamburger", "spaghettis", "pizza" };
int[] price = { 10, 15, 20, 5, 12 };
for (int i = 0; i < menu.length; i++) {
System.out.println("We have " + menu[i] + " for " + price[i] + "€");
}
boolean wantMore = true;
int answer = 0;
int yes = 1;
int no = 0;
List<String> Order = new ArrayList<String>();
List<Integer> TotalPrice = new ArrayList<Integer>();
Scanner keyboard = new Scanner(System.in);
System.out.println("What do you want to eat?");
do {
String userOrder = keyboard.next().toLowerCase();
for (int i = 0; i < menu.length; i++) {
if (userOrder.equals(menu[i])) {
Order.add(userOrder);
System.out.println("You ordered " + userOrder);
TotalPrice.add(price[i]);
break;
} else {
System.out.println("Sorry, we don't have that");
}
}
System.out.println("Want something more? Say YES with 1 and NO with 0");
answer = keyboard.nextInt();
if (answer == yes) {
wantMore = true;
System.out.println("What else do you want?");
} else if (answer == no) {
wantMore = false;
}
} while (wantMore);
int sum = TotalPrice.stream().mapToInt(Integer::intValue).sum();
System.out.println("Order finished! \nYour order have " + Order);
System.out.println("The total price is: " + sum);
}
}
答案 0 :(得分:0)
您要执行的操作是确定所选项目是否在菜单中,如果是,请对其进行排序并要求更多。如果它不在整个菜单中,则打印错误。如果将for
循环更改为
//flag to keep track of if the item exists in the menu
boolean exists = false;
for (int i = 0; i < menu.length; i++) {
//set exists to false at the beginning of the loop
exists = false;
if (userOrder.equals(menu[i])) {
Order.add(userOrder);
System.out.println("You ordered " + userOrder);
TotalPrice.add(price[i]);
//if the item exists in the menu, set the flag to true
exists = true;
}
}
//checks if the item was never found in the menu
if (!exists) {
System.out.println("Sorry, we don't have that");
}
看看您的程序是否给您带来更好的运气。
答案 1 :(得分:0)
首先遍历循环以找到匹配的顺序。如果不可用,则显示错误。
尝试一下:
boolean validMenuItem = false;
for (int i = 0; i < menu.length; i++) {
if (userOrder.equals(menu[i])) {
Order.add(userOrder);
System.out.println("You ordered " + userOrder);
TotalPrice.add(price[i]);
validMenuItem = true;
break;
}
}
if (!validMenuItem) {
// wrong input
System.out.println("Sorry, we don't have that");
}