为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

杨魅力 2021-12-30 16:21:46
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 回答

?
元芳怎么了

TA贡献1798条经验 获得超7个赞

您必须自己测试该元素在循环之后是否不存在boolean。此外,如果找到,则无需继续循环(所以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);

}


查看完整回答
反对 回复 2021-12-30
  • 1 回答
  • 0 关注
  • 187 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信