我试图确定字符串数组中的特定项是否是整数。
我是.split(" ")'ing中缀表达式的字符串形式,然后尝试将结果数组拆分为两个数组;一个用于整数,一个用于操作符,同时丢弃括号和其他杂项。实现这一目标的最佳方式是什么?
我想我可能能找到一个整数。isInteger(String arg)方法之类的,但没有这样的运气。
我试图确定字符串数组中的特定项是否是整数。
我是.split(" ")'ing中缀表达式的字符串形式,然后尝试将结果数组拆分为两个数组;一个用于整数,一个用于操作符,同时丢弃括号和其他杂项。实现这一目标的最佳方式是什么?
我想我可能能找到一个整数。isInteger(String arg)方法之类的,但没有这样的运气。
当前回答
或者简单地
mystring.matches(“\\d+”)
尽管对于大于int型的数字,它会返回true
其他回答
或者简单地
mystring.matches(“\\d+”)
尽管对于大于int型的数字,它会返回true
你可以使用integer . parseint (str),如果字符串不是一个有效的整数,以以下方式捕获NumberFormatException(正如所有答案所指出的那样):
static boolean isInt(String s)
{
try
{ int i = Integer.parseInt(s); return true; }
catch(NumberFormatException er)
{ return false; }
}
但是,请注意,如果计算的整数溢出,则会抛出相同的异常。你的目的是找出它是否是一个有效的整数。所以用你自己的方法来检查有效性会更安全:
static boolean isInt(String s) // assuming integer is in decimal number system
{
for(int a=0;a<s.length();a++)
{
if(a==0 && s.charAt(a) == '-') continue;
if( !Character.isDigit(s.charAt(a)) ) return false;
}
return true;
}
public boolean isInt(String str){
return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
"\\d+") : str.matches("\\d+");
}
最好像这样使用正则表达式:
str.matches("-?\\d+");
-? --> negative sign, could have none or one
\\d+ --> one or more digits
如果可以使用if-statement代替,那么在这里使用NumberFormatException是不好的。
如果你不想要前导0,你可以像下面这样使用正则表达式:
str.matches("-?(0|[1-9]\\d*)");
或者,您可以从Apache Commons的好朋友StringUtils那里获得一点帮助。isNumeric (String str)