简体   繁体   中英

Multiple and/or conditions in a java while loop

I want the while loop to execute when the user's input is a non-integer value, an integer value less than 1, or an integer value greater than 3. Once the input is valid, I will use it. However, the loop only works when the user inputs a non-integer value. I have gone through the logic and I am still not sure what's wrong.

Code:

  Scanner scnr = new Scanner(System.in);
  do {

     System.out.println("Please enter an integer value 1-3 for the row.");

     while((scnr.hasNextInt() && (scnr.nextInt() > 3)) || (scnr.hasNextInt() && (scnr.nextInt() < 1)) || (!scnr.hasNextInt()))
     {

        System.out.println("Your input is not valid.");
        System.out.println("Please enter an integer value 1-3 for the row.");
        scnr.next();
     }
     row = scnr.nextInt() - 1;

"while" works fine by itself. No "do" is required in this case. Here is your code:

 Scanner scnr = new Scanner(System.in);

 System.out.println("Please enter an integer value 1-3 for the row.");

     while((scnr.hasNextInt() && (scnr.nextInt() > 3)) || (scnr.hasNextInt() && (scnr.nextInt() < 1)) || (!scnr.hasNextInt()))
     {
        System.out.println("Your input is not valid.");
        System.out.println("Please enter an integer value 1-3 for the row.");
        scnr.next();
     }
     int row = scnr.nextInt() - 1;

You need "do" when you want to execute code at least once and then check "while" condition.

Also each call for nextInt actually requires next int in the input. So, better use it only once like this:

int i;
while((i=scnr.hasNextInt() && (i > 3)) || (scnr.hasNextInt() && (i < 1)) || (!scnr.hasNextInt()))

I am not completly sure about this, but an issue might be calling scnr.nextInt() several times (hence you might give the value to a field to avoid this). An easy to read solution would be introducing a tester-variable as @Vikrant mentioned in his comment, as example:

 System.out.println("Please enter an integer value 1-3 for the row.");
 boolean invalid=true;
 int input=-1;

 while(invalid)
 {
    invalid=false;
    if(scnr.hasNextInt())
         input=scnr.nextInt();
    else
         invalid=true;
    if(input>3||input<1)
         invalid=true;
    if(!invalid)
        break;
    System.out.println("Your input is not valid.");
    System.out.println("Please enter an integer value 1-3 for the row.");
    scnr.next();
 }

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