Your algorithm is really bad, very redundant. Besides, it is incorrect. According to you algorithm, for example, some strings containing only the characters '0' to '9' is always valid, but it cannot be a a valid number if it is too long.
You need a completely different approach. Simply call the function
parseDouble
with your input string:
http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble%28java.lang.String%29[
^].
From the documentation referenced above, you can see that
NullPointerException
or
NumberFormatException
can be thrown. Catch them both and return false; if the exception wasn't caught, return true. On top of it, you may want to add the validation for the range of the parsed number.
But even this code would be redundant. You simply don't need a validation function in this case (unless you also validated the range or something else); you should better do two things at a time: validate and obtain the numeric value from a string. If you want to wrap it in some function which will show validation result or return a valid numeric value, do it.
—SA