Every application should handle the exceptions gracefully. i.e.; application should report any errors that are encountered due to the data entered by the user. Java allows programmers to handle these situations with Exception handling technique.
In this post, I'm going to explain how we can implement a numeric validation on the string entered by the user. There are many different way to achieve this i.e.; we could use Regular expressions or we could handle with Wrapper classes.
The logic that I'm using here is very simple, try using Integer.parseInt method to covert string to an integer. If this method throws a NumberFormatException, then the string is not a numeric.
* A demo class to find out a given number numeric or not
* @author SANTHOSH REDDY MANDADI
* @version 1.0
* @since 10-December-2012
public class NumericValidation
public static void main(String args)
String str = "10dfsdf";
boolean number = false;
number = true;
number = false;
System.out.println(str+" is a number.");
System.out.println(str+" is not a number.");
10dfsdf is not a number.
104 is a number.
You could use Double.parseDouble() or Float.parseFloat() methods if you would like to validate the data for floating point values