How can I check if an integer is input or not in Java?
In my program, I want to enter an integer input by the user. I want the error message to be displayed when the user enters a value that is not an integer. How can i do this. My program is to find the area of ββthe circle. In which the user enters a radius value. But if the user enters a character, I want the message to be shown with 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);
source to share
If you are getting user input with Scanner
, you can do:
if(yourScanner.hasNextInt()) {
yourNumber = yourScanner.nextInt();
}
If you don't, you will need to convert it to int
and catch NumberFormatException
:
try{
yourNumber = Integer.parseInt(yourInput);
}catch (NumberFormatException ex) {
//handle exception here
}
source to share
Using Integer.parseIn (String), you can parse a string value to integer. Also you need to catch the exception if the input line is not the correct number.
int x = 0;
try {
x = Integer.parseInt("100"); // Parse string into number
} catch (NumberFormatException e) {
e.printStackTrace();
}
source to share
If the user input is String
, then you can try to parse it as an integer with the method parseInt
that throws NumberFormatException
when the input is not a valid numeric string:
try {
int intValue = Integer.parseInt(stringUserInput));
}(NumberFormatException e) {
System.out.println("Input is not a valid integer");
}
source to share
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.
}
source to share
String input = "";
int inputInteger = 0;
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
System.out.println("Enter the radious: ");
try {
input = br.readLine();
inputInteger = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("Please Enter An Integer");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
float area = (float) (3.14*inputInteger*inputInteger);
System.out.println("Area = "+area);
source to share
You can use try-catch block to check integer value
eg:
User inputs as 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());
}
source to share