Reputation: 14950
Good day!
I have a class Student with attribute String studentNo
Using OO, how can I validate if the input is an 11-digit no.
I can do this:
If(studentNo.length()<11){
}
to validate.. but how can I determine if it is a number or not.
And what are the other methods on how can I do this validation.
Any help would be highly appreciated. Thank you.
Upvotes: 0
Views: 793
Reputation: 3501
Semantically, you could use
try {
new BigInteger(studentNo);
} catch (NumberFormatException e) {
...
}
However, the regexp solutions might be more elegant with respect to the "don't use exceptions as a form of input checking" paradigm (exception handling is generally more expensive than simple checks). So, it depends on whether you want the code to be semantically clear or whether you want it to be efficient.
Upvotes: 0
Reputation: 75406
You can check the following:
For a complex check you frequently store the result in a boolean. First setting it to true and if any of the conditions fail you set it to false. You then know in the end if all conditions held, by seing that it is still true.
Upvotes: 3
Reputation: 1952
Use regex:
http://en.wikipedia.org/wiki/Regular_expression
For example, in java you would do this:
studentNo.matches("[0-9]{11}");
Upvotes: 0
Reputation: 48795
You would want to use a regular expression, like this:
^[0-9]{11}$
Upvotes: 5
Reputation: 2403
bool isNum = true;
try {
Integer.parseInt(studentNo);
}
catch (NumberFormatException e {
// if we hit here it is not a number...
isNum = false;
}
Upvotes: 2