I normally use the following idiom to check if a String can be converted to an integer.
public boolean isInteger( String input ) {
try {
Integer.
I believe there's zero risk running into an exception, because as you can see below you always safely parse int
to String
and not the other way around.
So:
You check if every slot of character in your string matches at least one of the characters {"0","1","2","3","4","5","6","7","8","9"}.
if(aString.substring(j, j+1).equals(String.valueOf(i)))
You sum all the times that you encountered in the slots the above characters.
digits++;
And finally you check if the times that you encountered integers as characters equals with the length of the given string.
if(digits == aString.length())
And in practice we have:
String aString = "1234224245";
int digits = 0;//count how many digits you encountered
for(int j=0;j
And the results are:
It's an integer!!
It's not an integer!!
Similarly, you can validate if a String
is a float
or a double
but in those cases you have to encounter only one . (dot) in the String and of course check if digits == (aString.length()-1)
Again, there's zero risk running into a parsing exception here, but if you plan on parsing a string that it is known that contains a number (let's say int data type) you must first check if it fits in the data type. Otherwise you must cast it.
I hope I helped