Issue with logic and Loop in Java

前端 未结 4 1742
感动是毒
感动是毒 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();
    } 
    
    0 讨论(0)
  • 2020-12-12 06:57

    This is a logical problem, the "choice" value should be either 1 or 2. In your (while) statement you are checking that "choice" is not different from 1 but also that "choice" is not different from 2. This condition is never reached because "choice" can be either 1 or 2 but not both values at the same time. This is only an explanation of the situation.

    0 讨论(0)
  • 2020-12-12 07:00

    Maybe you can try the following code. In your code , it's not need to use iteration.

    choice = input.nextInt();
    while (choice != 1 && choice != 2) {
        System.out.println("Invalid entry, press 1 or 2");
        choice = input.nextInt();
    }   
    
    0 讨论(0)
  • 2020-12-12 07:04

    Part of the problem is that you are recursively calling menuLoop from within menuLoop

    If you had a while loop within main then you could just do a return if the proper keys is not pressed.

    so main would be something like

    while (!menuLoop () {
      System.out.println("Invalid entry, press 1 or 2");
    }
    

    and menuLoop would return a boolean

    public static boolean MenuLoop() {
    
      ....
    
    System.out.println("1. Check for Number 1");
    System.out.println("2. Check for Number 2");
    System.out.print("Please enter your choice... ");
    choice = input.nextInt();
    if(choice != 1 && choice != 2) {   // and NOT or
        return false;
    }    
    
    switch (choice) {
    case 1:
        System.out.println("Pressed 1");
        break;
    case 2:
        System.out.println("Pressed 2");
        break;
    default:
        System.out.println("Invalid number");
    }
    return true;
    

    Also please remember that the scanner.nextInt will not swallow up the Enter that may or may not be pressed.

    0 讨论(0)
提交回复
热议问题