Issue with logic and Loop in Java

前端 未结 4 1750
感动是毒
感动是毒 2020-12-12 06:11

I started coding small program in Java. I wanted to exercise try-catch block, but i did not even come to that part and got stuck on loop part. I know this is very basic loop

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-12 06:47

    You need a logical and (not or) here

    while (choice != 1 || choice != 2) {
        System.out.println("Invalid entry, press 1 or 2");
        MenuLoop();
    } 
    

    should be something like

    while (choice != 1 && choice != 2) {
        System.out.println("Invalid entry, press 1 or 2");
        MenuLoop();
    } 
    

    or (using De Morgan's laws) like

    while (!(choice == 1 || choice == 2)) {
        System.out.println("Invalid entry, press 1 or 2");
        MenuLoop();
    } 
    

提交回复
热议问题