java - 如何使最后一个 else 语句只执行一次?(它正在执行5次)
问题描述
public static void main(String[] args) {
String[] items = { "Ham", "Ranch", "Plantains", "Soda", "Spaghetti" };
double[] prices = { 1.99, 2.99, 3.99, 4.99, 5.99 };
int[] inventory = { 100, 200, 300, 400, 500 };
System.out.printf("We have these items available: Ham, Ranch, Plantains, Soda, Spaghetti");
System.out.printf("\nSelect an Item ->");
Scanner input = new Scanner(System.in);
String item = input.nextLine();
for (int i = 0; i < items.length; i++) {
if (items[i].equals(item)) {
System.out.printf("\nYes, we have %s. Price:%s Inventory:%s", items[i], prices[i], inventory[i]);
System.out.print("\nHow many would you like to purchase? -->");
int quantity = input.nextInt();
if (inventory[i] >= quantity) {
double total = quantity * prices[i];
System.out.printf("\nThank you for your purchase of: Item: %s \nYour total bill is: %2.2f",
items[i], total);
}else {
System.out.printf("\nSorry, we only have Inventory:%s of Item: %s", inventory[i], items[i]);
}
}else {
System.out.printf("\nSorry, we don't have %s", item);
}
}
}
}
所以,最后一个 else 语句打印了 5 次而不是 1 次,我不知道该怎么做才能修复它。它在右括号之间吗?
解决方案
您必须自己使用变量测试循环后元素是否不存在。boolean
此外,如果找到它,则无需继续循环(so break
)。并使用%n
withprintf
获取换行符。像,
boolean found = false;
for (int i = 0; i < items.length; i++) {
if (items[i].equals(item)) {
System.out.printf("%nYes, we have %s. Price:%s Inventory:%s", items[i],
prices[i], inventory[i]);
System.out.print("%nHow many would you like to purchase? -->");
int quantity = input.nextInt();
if (inventory[i] >= quantity) {
double total = quantity * prices[i];
System.out.printf("%nThank you for your purchase of: Item: %s %n"
+ "Your total bill is: %2.2f", items[i], total);
} else {
System.out.printf("%nSorry, we only have Inventory:%s of Item: %s",
inventory[i], items[i]);
}
found = true;
break;
}
}
if (!found) {
System.out.printf("%nSorry, we don't have %s", item);
}
推荐阅读
- prolog - Prolog - 实施埃拉托色尼筛法的麻烦
- css - 如何将 :before 伪类与 :not 伪类一起使用?
- r - 为什么 strsplit("A, B . C",c(", ",". ")) 不删除 ". "?
- youtube - 上传最新公开视频的 Youtube iframe 代码
- powershell - 如何将 psm1 和 psd1 文件合并为一个 powershell 函数?
- bash - shell:将十进制转换为本机十六进制数
- c# - Google 日历问题 - 接口和导入
- android-studio - 如何可变地添加到arrayOf
() 在 Kotlin 中? - javascript - 将图像 url 转换为文件 JavaScript
- android - 是否可以创建一个APK来安装媒体文件,没有应用程序