如何使最后的else语句仅执行一次? (执行5次)

时间:2018-11-04 23:57:23

标签: java arrays for-loop if-statement

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次而不是打印5次,我不确定该如何解决。是在右括号之间吗?

1 个答案:

答案 0 :(得分:0)

您将必须使用循环变量boolean自己测试循环后 是否不存在该元素。另外,如果找到它,则无需继续循环(因此break)。并将%nprintf一起使用以获取换行符。喜欢,

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