|
How to use Exception classes to validate Numbers |
|
|
This code will show how to use NumberForamtException to validate whether given string contains a valid integer or not.
parseInt() method of the Integer object uses to convert a given string to the integer. This method throws a NubmerPointerException if the given string is not a valid integer.
public class NmbrVldExp {
public static boolean validateNumber(String num) {
try {
Integer.parseInt(num);
return true;
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
String num="6";
if(validateNumber(num)){
System.out.println("Correct Number");
}else{
System.out.println("Incorrect Number");
}
}
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.