0

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.

3

5 Answers 5

3

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!");
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

0

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.

Comments

0

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.