Как сделать, чтобы последний оператор else выполнялся только один раз? (Выполняется 5 раз) - PullRequest
0 голосов
/ 05 ноября 2018
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 Ответ

0 голосов
/ 05 ноября 2018

Вам придется проверить, присутствует ли элемент после цикла с переменной boolean. Также, если он найден, нет необходимости продолжать зацикливание (поэтому break). И используйте %n с printf, чтобы получить перевод строки. Как,

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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...