In my program I want an integer input by the user. I want an error message to be show when user inputs a value which is not an integer. How can I do this. My program is to find area of circle. In which user will input the value of radius. But if user inputs a character I want a message to be shown saying Invalid Input.
This is my code:
int radius, area;
Scanner input=new Scanner(System.in);
System.out.println("Enter the radius:\t");
radius=input.nextInt();
area=3.14*radius*radius;
System.out.println("Area of circle:\t"+area);
hasNextInt() method checks whether the current input contains an integer or not. If the integer occurred in input this method will return true otherwise it will return false.
Input the data. Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int.
The hasNextDouble() is a method of Java Scanner class which is used to check if the next token in this scanner's input can be interpreted as a double value using the nextDouble() method. It returns true if the scanner's input can be interpreted as a double value, otherwise returns false.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With