how to end a while loop with a certain variable

后端 未结 4 565
谎友^
谎友^ 2021-01-17 02:28

I am making an odd or even program with a while loop. I am trying to figure out how to end the while loop with a certain number. Right now I have 1 to continue the loop, and

4条回答
  •  心在旅途
    2021-01-17 03:11

    I did not follow the conditions you wanted exactly because it does not make sense to have a continue condition AND a terminate condition unless there are other options.

    What did you want the user to do if he entered 3, 4 or 5? Exit the code or continue the code? Well if the default is to exit, then you do not need the code to exit on 2 because it already will! If the default is to continue, then you do not need the continue on 1 and only the exit on 2. Thus it is pointless to do both in this case.

    Here is the modified code to use a do while loop to ensure the loop is entered at least 1 time:

        int x;
        do {
            System.out.println("Enter a number to check whether or not it is odd or even");
            Scanner s = new Scanner(System.in);
            int num = s.nextInt();
            if (num % 2 == 0)
                System.out.println("The number is even");
            else 
                System.out.println("The number is odd");
            //trying to figure out how to get the code to terminate if you put in a value that isn't a number
            System.out.println("Type 1 to check another number, anything else to terminate.");
    
            if (!s.hasNextInt()) {
                break;
            }
            else {
                x = s.nextInt();
            }
        } while(x == 1);
       }
    

    Note that I added a check to !s.hasNextInt() will check if the user enters anything other than an int, and will terminate without throwing an Exception in those cases by breaking from the loop (which is the same as terminating the program in this case).

    If the x is a valid integer, then x is set to the value and then the loop condition checks if x is 1. If x is not 1 the loop terminates, if it is it will continue through the loop another time.

提交回复
热议问题