猿问

我怎样才能让最后一个 else 语句只执行一次?

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 次而不是一次,我不知道该怎么做才能修复它。是否在右括号之间?


杨魅力
浏览 188回答 1
1回答

元芳怎么了

您必须自己测试该元素在循环之后是否不存在boolean。此外,如果找到,则无需继续循环(所以break)。并使用%nwithprintf获取换行符。喜欢,boolean found = false;for (int i = 0; i < items.length; i++) {&nbsp; &nbsp; if (items[i].equals(item)) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%nYes, we have %s. Price:%s Inventory:%s", items[i],&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prices[i], inventory[i]);&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("%nHow many would you like to purchase? -->");&nbsp; &nbsp; &nbsp; &nbsp; int quantity = input.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; if (inventory[i] >= quantity) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; double total = quantity * prices[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%nThank you for your purchase of: Item: %s %n"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + "Your total bill is: %2.2f", items[i], total);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%nSorry, we only have Inventory:%s of Item: %s",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; inventory[i], items[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; found = true;&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }}if (!found) {&nbsp; &nbsp; System.out.printf("%nSorry, we don't have %s", item);}
随时随地看视频慕课网APP

相关分类

Java
我要回答