Reputation: 33
new programmer here.
Just a quick question - as mentioned already in the Title:
How do I output an error message for a non-numeric input ?
Example, person enters a letter for an int classified input - the compiler produces an error of: "Exception in thread "main" java.util.InputMismatchException"
How do I actually make it output an error message within the program itself?
Cause I'm wanting the program to keep looping to request an input again til a specified requirement has been met to exit the program.
Upvotes: 0
Views: 11607
Reputation: 34424
You need to do it programmatically. Put your suspected code under try catch block and in case exception print/or throw required error message. For example if you want to print error message if user enters number less than 10
Scanner user_input = new Scanner( System.in );
int numberEntered=user_input.nextInt();
while(numberEntered<=10)
{
System.out.println("Please enter number greater than 10");
}
Upvotes: 0
Reputation: 10270
You have to put your parsing in a try-catch
statement:
try {
int number = Integer.parseInt(yourString);
} catch (NumberFormatException ex) {
System.out.println("Not a valid number!");
}
Upvotes: 3
Reputation: 137282
The message that you described is resulted from an Exception (tutorial) that was not handled by your program.
You can handle such an exception using the try-catch construct.
try
{
// Getting a number from input
}
catch(InputMismatchException ex)
{
// do something to recover.
}
As a side note - the exception is thrown by the Java runtime, and not by the compiler.
Upvotes: 2