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

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

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


当前回答

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

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

其他回答

最好像这样使用正则表达式:

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*)");

作为尝试解析字符串并捕获NumberFormatException的另一种方法,您可以使用regex;如。

if (Pattern.compile("-?[0-9]+").matches(str)) {
    // its an integer
}

这可能更快,特别是在预编译和重用正则表达式的情况下。

然而,这种方法的问题是,如果str表示的数字超出了合法int值的范围,Integer.parseInt(str)也会失败。虽然可以创建一个只匹配Integer范围内的整数的正则表达式。MIN_INT到Integer。MAX_INT,这不是一个漂亮的景象。(我不打算尝试……)

另一方面……出于验证目的,将“不是整数”和“整数太大”分开处理是可以接受的。

或者,您可以从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+");
}