0

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;
1
  • I think that your problem is that you use scnr.nextInt() two times in the same while. If I were you I would use: int myInput = scnr.nextInt(); while(myInput>3 || myInput <1) ... Commented Feb 17, 2016 at 16:01

2 Answers 2

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()))
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.