This question already has an answer here:
I'm trying to determine if a particular item in an Array of strings is an integer or not.
I am .split(" ")'ing
an infix expression in String
form, and then trying to split the resultant array into two arrays; one for integers, one for operators, whilst discarding parentheses, and other miscellaneous items. What would be the best way to accomplish this?
I thought I might be able to find a Integer.isInteger(String arg)
method or something, but no such luck.
Or you can enlist a little help from our good friends at Apache Commons : StringUtils.isNumeric(String str)
The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.
Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.
If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:
As an alternative to trying to parse the string and catching
NumberFormatException
, you could use a regex; e.g.This is likely to be faster, especially if you precompile and reuse the regex. However, the catch is that
Integer.parseInt(str)
will still fail ifstr
represents a number that is outside range of legalint
values.You can use
Integer.parseInt(str)
and catch theNumberFormatException
if the string is not a valid integer, in the following fashion (as pointed out by all answers):However, note here that if the evaluated integer overflows, the same exception will be thrown. Your purpose was to find out whether or not, it was a valid integer. So its safer to make your own method to check for validity:
You want to use the Integer.parseInt(String) method.