I need to convert an String
to Integer
but first I have to make sure it's a number. In C# I use int.TryParse
or "".All(Char.IsNumber)
but apparently there is no such thing in Java.
I need to convert an String
to Integer
but first I have to make sure it's a number. In C# I use int.TryParse
or "".All(Char.IsNumber)
but apparently there is no such thing in Java.
Code
Result
Number
String
Explanation
Using the possible exception that the Integer.parseInt() function throws , it is enough to enclose
try/catch
the conversion of the string to a number in a .When the type exception
NumberFormatException
occurs, then we determine that the conversion failed and therefore the string that was attempted to be converted is not a number, returningFALSE
. Otherwise, it returns aTRUE
.See an example
If you do not use any external library that provides the functionality, it is best to define a utility class with a method that does the checking, similar to:
The reason it doesn't exist
TryParse
is because it's already implied.If you check the prototype of
Integer.parseInt
you can see that the method throws an exception when passing a string without a valid integer.NumberFormatException is a checked exception. Java has two types of exceptions: checked and unchecked, the first type ALWAYS forces to enclose the call with the blocks
try...catch
to the method that throws it, while the second type does not.If we parse the flow in C#
The equivalent in Java is
As you can see
TryParse
it is implicit as itparseInt
throws an exception, which changes the flow of the program automatically.P.S.
Any implementation of is discouraged
TryParse
since, unlike C#, the primitive types in Java are always passed by value, this means that the proposed method would require parsing the string twice, once to return if the string actually contains an integer and the other to get its value, which is absurd.An alternative to verify that the String only has digits as a character is always to go through the String and verify it so you avoid the exception.
Edit: It is only valid for positive numbers, in the case of negatives you would have to make an extra purchase for the negative symbol.