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.
You can use
Integer.parseInt()
orInteger.valueOf()
to get the integer from the string, and catch the exception if it is not a parsable int. You want to be sure to catch theNumberFormatException
it can throw.It may be helpful to note that valueOf() will return an Integer object, not the primitive int.
Or simply
mystring.matches("\\d+")
though it would return true for numbers larger than an int
Using regular expression is better.
It is not good to use
NumberFormatException
here if you can useif-statement
instead.If you don't want leading zero's, you can just use the regular expression as follow: