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

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

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


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

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

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

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

最简单的方法是遍历String,并确保所有元素都是给定基数的有效数字。这是最有效的方法,因为每个元素至少要看一次。我认为我们可以基于基数进行微优化,但无论如何,这都是你所期望得到的最好结果。

public static boolean isInteger(String s) {
    return isInteger(s,10);
}

public static boolean isInteger(String s, int radix) {
    if(s.isEmpty()) return false;
    for(int i = 0; i < s.length(); i++) {
        if(i == 0 && s.charAt(i) == '-') {
            if(s.length() == 1) return false;
            else continue;
        }
        if(Character.digit(s.charAt(i),radix) < 0) return false;
    }
    return true;
}

或者,您也可以依赖Java库来实现此功能。它不是基于异常的,并且将捕获您能想到的几乎所有错误条件。这样做的代价会稍微高一些(您必须创建一个Scanner对象,在一个非常严格的循环中,您不希望这样做。但它通常不会太贵,所以对于日常操作来说应该是相当可靠的。

public static boolean isInteger(String s, int radix) {
    Scanner sc = new Scanner(s.trim());
    if(!sc.hasNextInt(radix)) return false;
    // we know it starts with a valid int, now make sure
    // there's nothing left!
    sc.nextInt(radix);
    return !sc.hasNext();
}

如果最佳实践对你来说不重要,或者你想要骚扰做你代码审查的人,试试这个:

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    } catch(NullPointerException e) {
        return false;
    }
    // only got here if we didn't return false
    return true;
}

作为尝试解析字符串并捕获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 (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;
}

或者简单地

mystring.matches(“\\d+”)

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

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

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*)");
public boolean isInt(String str){
    return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
            "\\d+") : str.matches("\\d+");
}