有机会简化这些嵌套循环吗?

问题描述 投票:0回答:1

我正在为我的学校项目创建一个购物车管理器,并且有一种方法可以从购物车中删除一个项目。

        public String removeItem(String itemName) {
            String removeOutput = "Something is wrong";
            int CAPACITY = 10;
            ShoppingCartManager SCM = new ShoppingCartManager();
            System.out.println("Enter name of the item:");
            itemName = SCM.input.nextLine();
            for(int i=0; i < CAPACITY; i++) {
                if(itemNames[i] != null) {
                    if(itemNames[i].equals(itemName)) {
                        itemNames[i] = null;
                        costs[i] = 0;
                        for(int j=0; j < CAPACITY; j++) {
                            if(cartItems[j].toString().contains(itemName)) {
                                for(int k = 0; k < quantities[i]; k++) {
                                    cartItems[j + k] = null;
                                }
                                break;
                            } 
                        }
                        quantities[i] = 0;
                        removeOutput = ("["+itemName+"] is removed from your shopping cart. ");
                        break;
                    } else {
                        removeOutput = ("["+itemName+"] not found in cart. ");
                    }
                }
                
            }
            return removeOutput;
        }

这是我能做的最好的,结果也符合预期,我只是好奇是否有可能简化方法中的超长嵌套循环。

java nested-loops
1个回答
0
投票

您还可以使用保护子句来“取消嵌套”嵌套的 if 语句。这是您指定跳过数据的条件,而不是您想要继续处理数据所需的条件

if(itemNames[i] != null) {
    if(itemNames[i].equals(itemName)) {
        //... more nested loops etc.
    }
}

可提取用于:

if(itemNames[i] == null) {
    return;  //or break/continue depending if its inside a loop or a function
}
//other guard clause if statements
if(itemNames[i].equals(itemName)) {
    //... processing
}

当然,如果您有更多 if 条件嵌套,则可以将它们全部提取出来以使其更具可读性。

至于嵌套 for 循环,这取决于您对使用数据结构的过程的认识程度。你能在一个for循环中完成吗?你能否将其中一个循环提取到一个方法中并调用它,以便代码看起来更具可读性,即使它仍然是一个嵌套的 for 循环?

© www.soinside.com 2019 - 2024. All rights reserved.