I'm having trouble with my code.
What it should do:
- Check if Scanner "myScanner" is an Integer
- If it is an Integer, if it is between 1 and 200 (both included)
Problem:
- I need to input an Integer with the correct value twice after the the first guess wasn't correct.
Here is a screenshot of exactly what I mean: Screenshot of the problem
private static int inputGuess () {
Scanner myScanner = new Scanner(System.in);
int guess = 0;
if (myScanner.hasNextInt()) {
guess = myScanner.nextInt();
}
if (1 > guess || guess > 200) {
while (!(myScanner.hasNextInt()) || !(1 <= guess && guess <= 200)) {
while (!myScanner.hasNextInt()) {
myScanner.nextLine();
}
guess = myScanner.nextInt();
if (!(guess >= 1 && guess <= 200)) {
myScanner.nextLine();
}
}
}
return guess;
}
I have tried to apply @Hulk's (top answer) logic (at least I think I did) into a single method (is sadly a requirement for my project) and got this:
private static int inputGuess () {
Scanner myScanner = new Scanner(System.in);
int guess = 0;
while (!myScanner.hasNextInt() || guess < 1 || guess > 200) {
while (!myScanner.hasNextInt()) {
myScanner.nextLine();
}
guess = myScanner.nextInt();
if (guess >= 1 && guess <= 200) {
break;
}
}
return guess;
}
After a bit of testing still no error! If you still find a mistake I would be happy if you shared it with me!