I am trying to make a loop that prompts the user for a positive integer so it can be saved into int x.
If a negative or non-integer is entered it will prompt the user again.
It seems to work when a negative value is entered, but not when an exception is entered.
When an exception is entered it just endlessly prints "Please enter a positive integer." without allowing input.
What am I doing wrong? Please help guide me.
Thanks in advance.
int x = 0;
boolean firstLoop = false;
while (firstLoop == false)
{
firstLoop = true;
try
{
x = in.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("Please enter a positive integer.");
firstLoop = false;
}
if (x < 0)
{
System.out.println("Please enter a positive integer.");
firstLoop = false;
}
}
CodePudding user response:
If you type in an illegal character that can't be parsed to an int, you will get an InputMismatchException
. Since firstloop
is set to false, the loop continues. But the illegal character is still in the buffer so it continues to repeat. So do something like in.nextLine();
in the first catch block to start over and clear the bad character including the newline.
CodePudding user response:
You miss in.hasNextInt()/in.hasNextLine()/in.nextLine()
.
If you can do without console in the IDE, better use java.io.Console
instead
of Scanner on System.in.
You then need to convert yourself: int Integer.parseInt(String)
but it is much cleaner, and allows better prompts.
Console con = System.console();
int x = 0;
for (;;) {
String input = con.readLine("Please enter a positive integer <= %d: ",
Integer.MAX_VALUE);
if (input == null) { // User ended console.
break;
}
if (input.matches("\\d ")) { // 1 or more digits.
x = Integer.parseInt(input);
break;
} else {
con.printf("This '%s' is not a positive integer.%n", input);
}
}