dimanche 4 novembre 2018

How can I make the last else statement only execute once? (It is executing 5 times)

public static void main(String[] args) {
    String[] items = { "Hammer", "Wrench", "Pliers", "Saw", "ScrewDriver" };
    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: Hammer, Wrench, Pliers, Saw, ScrewDriver");

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

    }
}

}

So, the last else statement is printing out 5 times rather than one, I am not sure what to do in order to fix it. Is it in between the right brackets?

Aucun commentaire:

Enregistrer un commentaire