Daedius
Daedius

Reputation: 33

How do I output an error message for a non-numeric input?

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

Answers (5)

M Sach
M Sach

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

Raul Rene
Raul Rene

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

MByD
MByD

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

JHS
JHS

Reputation: 7871

You could check the input by using the isNumeric method from the NumericUtils class. The class is from the org.apache.commons.lang.math package.

You can have a look at the java docs

If this method returns false then display the corresponding error.

Upvotes: 0

The Cat
The Cat

Reputation: 2475

You can try and parse the input as a number and catch a NumberFormatException. Consider using Integer.valueOf(String). This will throw a NumberFormatException if the input is not a valid integer. You can catch this exception using a try-catch block.

Upvotes: 0

Related Questions