我试图确定字符串数组中的特定项是否是整数。

我是.split(" ")'ing中缀表达式的字符串形式,然后尝试将结果数组拆分为两个数组;一个用于整数,一个用于操作符,同时丢弃括号和其他杂项。实现这一目标的最佳方式是什么?

我想我可能能找到一个整数。isInteger(String arg)方法之类的,但没有这样的运气。


当前回答

或者,您可以从Apache Commons的好朋友StringUtils那里获得一点帮助。isNumeric (String str)

其他回答

或者简单地

mystring.matches(“\\d+”)

尽管对于大于int型的数字,它会返回true

你需要使用Integer.parseInt(String)方法。

try{
  int num = Integer.parseInt(str);
  // is an integer!
} catch (NumberFormatException e) {
  // not an integer!
}

或者,您可以从Apache Commons的好朋友StringUtils那里获得一点帮助。isNumeric (String str)

您可以使用integer . parseint()或integer . valueof()从字符串中获取整数,如果它不是一个可解析的int,则捕获异常。您希望确保捕获它可以抛出的NumberFormatException。

注意valueOf()将返回一个Integer对象,而不是原语int,这可能会有所帮助。

public boolean isInt(String str){
    return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
            "\\d+") : str.matches("\\d+");
}