How to check the input is an integer or not in Java? [duplicate]
If you are getting the user input with Scanner
, you can do:
if(yourScanner.hasNextInt()) {
yourNumber = yourScanner.nextInt();
}
If you are not, you'll have to convert it to int
and catch a NumberFormatException
:
try{
yourNumber = Integer.parseInt(yourInput);
}catch (NumberFormatException ex) {
//handle exception here
}
You can try this way
String input = "";
try {
int x = Integer.parseInt(input);
// You can use this method to convert String to int, But if input
//is not an int value then this will throws NumberFormatException.
System.out.println("Valid input");
}catch(NumberFormatException e) {
System.out.println("input is not an int value");
// Here catch NumberFormatException
// So input is not a int.
}
If the user input is a String
then you can try to parse it as an integer using parseInt
method, which throws NumberFormatException
when the input is not a valid number string:
try {
int intValue = Integer.parseInt(stringUserInput));
}(NumberFormatException e) {
System.out.println("Input is not a valid integer");
}
You can use try-catch block to check for integer value
for eg:
User inputs in form of string
try
{
int num=Integer.parseInt("Some String Input");
}
catch(NumberFormatException e)
{
//If number is not integer,you wil get exception and exception message will be printed
System.out.println(e.getMessage());
}