我已经在这个问题上工作了好几个小时,但是无法理解。我通过用户输入获取字符串变量并将其与数组中的值进行比较。当数组中存在值时,第一个if语句执行正常。但是,无论该值是否存在,第二个if语句在执行时只应在数组中不存在该值时执行。
// begin the calculate() function on the condition that XXX is not typed
while (addIn.compareTo("XXX") != 0) {
for (x = 0; x < NUM_ITEMS; x++) {
if (addIn.compareTo(addIns[x]) == 0) {
System.out.println("The price of " + addIn + " is $" + addInPrices[x]);
orderTotal += addInPrices[x];
}
if (addIn.compareTo(addIns[x]) != 0) {
System.out.println("Sorry, we don't carry that.");
addIn = JOptionPane.showInputDialog("Enter coffee add-in or " + END + " to quit: ");
}
}
addIn = JOptionPane.showInputDialog("Enter your next add-in, or XXX to complete your order!");
}
System.out.println("Your total is $" + orderTotal + ". Your order will be out shortly!");
我做错了什么?
答案 0 :(得分:0)
您正在为数组中的每个非匹配项执行第二条语句。你需要做的是设置一个标志并在循环结束时检查它:
// begin the calculate() function on the condition that XXX is not typed
while (addIn.compareTo("XXX") != 0) {
boolean found = false;
for (x = 0; x < NUM_ITEMS; x++) {
if (addIn.compareTo(addIns[x]) == 0) {
found = true;
System.out.println("The price of " + addIn + " is $" + addInPrices[x]);
orderTotal += addInPrices[x];
break;
}
}
if (!found) {
System.out.println("Sorry, we don't carry that.");
addIn = JOptionPane.showInputDialog("Enter coffee add-in or " + END + " to quit: ");
} else {
addIn = JOptionPane.showInputDialog("Enter your next add-in, or XXX to complete your order!");
}
}