I’m trying to write a Java program that asks the user to input a positive integer inside a while
loop. The loop should continue until valid input is provided.
I’ve tried using a try/catch
block to handle invalid inputs like strings, but I’m still running into issues. For example:
When the user enters a string, the program throws an InputMismatchException
and skips re-prompting the user.
I tried adding scanner.nextLine()
to clear the input buffer, but it didn’t work as expected.
Here’s the code I’ve written so far:
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int userInput = -1;
while (userInput < 0) {
try {
System.out.print("Enter a positive number: ");
userInput = scanner.nextInt(); // Crashes if invalid input is entered
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid number.");
scanner.nextLine(); // Attempt to clear the buffer, but it doesn't work
}
}
System.out.println("You entered: " + userInput);
scanner.close();
}
}
The issue:
When invalid input (like a string) is entered, the program skips re-prompting the user.
I suspect there’s an issue with how I’m clearing the input buffer using scanner.nextLine().
What I’ve tried:
Wrapping the scanner.nextInt() inside a try/catch block to catch the exception.
Using scanner.nextLine() after catching the exception to clear the input.
My question:
How can I properly handle invalid input in this scenario so that the program keeps re-prompting the user until a valid positive integer is provided?
Perhaps try something like:
String userInput = "";
while (true) { // loop until valid input
userInput = scanner.nextLine();
if (isInteger(userInput))
break;
System.out.print("Please enter a valid number.");
}
private static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch(NumberFormatException e) {
return false;
}
These previous answers may also help: https://stackoverflow.com/a/53904761/6423542 https://stackoverflow.com/a/24836513/6423542