Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the input is an integer or not in Java? [duplicate]

Tags:

java

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);
like image 640
Belal Khan Avatar asked Nov 12 '13 09:11

Belal Khan


People also ask

How do you check if the input is an integer in Java?

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.

How do you check if an input is an integer?

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.

How do you check if an input is a double Java?

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.


2 Answers

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
}
like image 77
BackSlash Avatar answered Nov 15 '22 07:11

BackSlash


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.
 } 
like image 38
Ruchira Gayan Ranaweera Avatar answered Nov 15 '22 08:11

Ruchira Gayan Ranaweera