首页 > 解决方案 > 如何使最后一个 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 次,我不知道该怎么做才能修复它。它在右括号之间吗?

标签: javaarraysfor-loopif-statement

解决方案


您必须自己使用变量测试循环元素是否不存在。boolean此外,如果找到它,则无需继续循环(so break)。并使用%nwithprintf获取换行符。像,

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);
}

推荐阅读