0

I am attempting to create a (very) simple menu/sub-menu navigation system that resembles a (very) basic online shopping application.
The problem I am getting is that once I have entered the sub-menu (by entering 2 in the top-level menu), I am not able to leave the sub-menu; even when entering 3 or 4. I'm not sure why this is happening and any help would be appreciated.

       while (subChoice != 3 || subChoice != 4) {
            subMenu();
            subChoice = getChoice(1, 4);
            if (subChoice == 1) {
                // Add items
                System.out.println("add");
            } else if (subChoice == 2) {
                // Remove items
                System.out.println("delete");
            } else if (subChoice == 3) {
                // Check out
                System.out.println("check out");
            } else if (subChoice == 4) {
                // Discard cart
                System.out.println("discard");
            }
        }
4

1 回答 1

2

while (subChoice != 3 || subChoice != 4) { is testing if subChoice is NOT 3 or is NOT 4. It can't be both at the same time, so the loop never ends. To fix it, use either one of these:

while (subChoice != 3 && subChoice != 4) {
    ...
}
while (!(subChoice == 3 || subChoice == 4)) {
    ...
}
于 2013-05-08T11:53:36.553 回答