0

I would like to use a single scanner input as multiple conditions in while loop where are can check if the input is correct or not and if its not correct to re-enter the input value.

Something like this:

while(scannerInput is a int AND scannerInput is > than 0 AND scannerInput is < 10)
{
    //CODE
}

but if I use scanner.hasNextInt() and scanner.nextInt() it prompt me for input instead of using the same one

while (scaner.hasNextInt() && scaner.nextInt() > 0 && scaner.nextInt() < 10)  {

}

Is there a way to store the first input and to re-use it again and again or is there a better solution to my problem ?

2

3 Answers 3

2

The call of scanner.nextInt() advances the position at which the scanner reads its input, so the second read may produce a different number, or throw an exception when there is only one int available. To work around this situation you could introduce a variable to hold the value for the second check:

int tmp;
while (scaner.hasNextInt() && (tmp = scaner.nextInt()) > 0 && tmp < 10)  {
    ...
}

The second subexpression (tmp = scaner.nextInt()) reads the next integer value from the scanner, and stores it in a temporary variable tmp. After that, the value is compared with zero, and finally the same value is compared to 10.

The assignment is performed before the check of tmp < 10 because parts of && expressions are processed in left to right order.

This solution is not ideal, because tmp remains visible after the loop, and because it is not so easy to read. You would be better off moving the check inside the loop, like this:

while (scaner.hasNextInt()) {
    int val = scaner.nextInt();
    if (val < 0 || val >= 10) {
        break;
    }
    ...
}

My idea was the code to keep prompting you for new input until its correct

A common way to achieve this is with a do/while loop:

int val = -1;
do {
    System.out.print("Enter an int: ");
    if (scanner.hasNextInt()) {
        val = scanner.nextInt();
    } else {
        scanner.nextLine();
    }
} while (val < 0 || val >= 10);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes but in this case I wont be propted direcrtly to type in new input, I will have to navigate back to this method, my idea was the code to keep prompting you for new input until its correct
0

try this code:

int s;
while (scanner.hasNext() && (s = scanner.nextInt()) >0 && s <0){
 #code          
}

Comments

0

You have some options here.

  1. You could put an if condition inside the while and give while a true as condition.. let the if statement break the while loop
  2. you could write a method which does the checks and give scanner.nextInt() as parameter

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.