There are some situation that I need to convert string to float or some other numerical data-type but there is a probability of getting some nonconvertible values such as “-” or “/” and I can’t verify all the values beforehand to remove them.
and I want to avoid using try/catch for this matter , is there any other way of doing a proper conversion in java? something similar to C# TryParse?
There are some situation that I need to convert string to float or some
Share
The simplest thing I can think of is
java.util.Scanner. However this approach requires a new Scanner instance for each String.Next you could write a regex pattern that you use to check the String (complex to fail too big values) and then call Integer.parseInt() after checking the string against it.
However both of these parse the string twice, once to test the string and a second time to get the value. Depending on how often you get invalid strings catching an exception may be faster.