Home > Software design >  Why 2D array for-loop checking cannot access some values?
Why 2D array for-loop checking cannot access some values?

Time:11-22

private static String[][] menuList = {{"Soda","10"},{"Coke","20"},{"Water","5"}};

public Drinks(String menu, String size) {
    setMenu(menu);
    setSize(size);
}

public void setMenu(String menu) {
    this.menu = menu;
    for (int i = 0; i < menuList.length; i  ) {
        if (this.menu.equalsIgnoreCase(menuList[i][0])){
            price = Double.valueOf(menuList[i][1]);
        }else{price = 0.0;}
    }
}

Then I create object for testing
I can't get price of the first two rows in menuList[][] but I can still get the last one

    Drinks d = new Drinks("water","L");
    Drinks e = new Drinks("coke","L");
    Drinks f = new Drinks("soda","L");
    System.out.println(d);
    System.out.println(e);
    System.out.println(f);

the output is

Drink[menu = water , size = L , price = 5.00]
Drink[menu = coke , size = L , price = 0.00]
Drink[menu = soda , size = L , price = 0.00]

I just want to know why? And how can I fix this?

CodePudding user response:

What you are actually doing is, for each entry in menuList, you check if it's name corresponds to your parameter, and set (i.e. overwrite) the price field every time. It works the same as if you didn't loop but only checked the last item.

There The solution is to break out of the loop. I also changed where you initialize the variable to make sure it's initialized at all.

public void setMenu(String menu) {
    this.menu = menu;
    price = 0.0;
    for (int i = 0; i < menuList.length; i  ) {
        if (this.menu.equalsIgnoreCase(menuList[i][0])){
            price = Double.valueOf(menuList[i][1]);
            break;
        }
    }
}
  • Related