Determine if a String is an Integer in Java [dupli

2018-12-31 12:36发布

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.

标签: java string int
9条回答
何处买醉
2楼-- · 2018-12-31 13:29

You can use Integer.parseInt() or Integer.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 the NumberFormatException it can throw.

It may be helpful to note that valueOf() will return an Integer object, not the primitive int.

查看更多
何处买醉
3楼-- · 2018-12-31 13:35

Or simply

mystring.matches("\\d+")

though it would return true for numbers larger than an int

查看更多
冷夜・残月
4楼-- · 2018-12-31 13:38

Using regular expression is better.

str.matches("-?\\d+");


-?     --> negative sign, could have none or one
\\d+   --> one or more digits

It is not good to use NumberFormatException here if you can use if-statement instead.


If you don't want leading zero's, you can just use the regular expression as follow:

str.matches("-?(0|[1-9]\\d*)");
查看更多
登录 后发表回答