简体   繁体   中英

Can not exit (nested) while loop - Java

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");
            }
        }

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)) {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM