0

我正在尝试确定字符串是否包含正整数。我的代码是:

public void isInt(String str) throws NotIntException{
    String integer=str.replaceAll("\\d","");
    System.out.println(integer);
    if (!integer.equals("")){
        throw new NotIntException("Wrong data type-check fields where an integer"+
        " should be.");
    }//end if
    if (integer.equals("-")){
        System.out.println(integer);
        throw new NotIntException("Error-Can't have a negative count.");
    }//end if
}//end method

我正在用字符串“-1”对此进行测试,它应该在 replaceAll() 之后变为“-”。这应该输入两个 if 语句。但它只进入第一个。我也尝试了 == 比较,以防万一,但它也不起作用。对我来说奇怪的是,无论我是要满足第二个 if 语句的条件还是满足它的否定 [即,!integer.equals("-")],程序仍然没有进入 if....

谢谢,通常我的比较问题只是我缺少一些基本的东西,但我真的没有在这里看到任何东西......

4

4 回答 4

3

由于您在第一个 if 中抛出异常,因此,您的第二个 if 甚至都不会被测试。

if (!integer.equals("")){
    throw new NotIntException("Wrong data type-check fields where an integer"+
    " should be.");
}

if (integer.equals("-")){
    System.out.println(integer);
    throw new NotIntException("Error-Can't have a negative count.");
}

如果您的代码输入第一个if,它将不会进一步执行。


但是,你为什么要使用这种方法来解决你的问题。

您可以轻松地使用Integer.parseInt来检查有效的integer. 然后如果它是有效的,然后测试它是否less than 0. 它会更容易和可读。

于 2012-11-08T22:32:34.000 回答
1

我的解决方案:

public static boolean isPositiveInt(String str) {
    try {
       int number = Integer.parseInt(str.trim());
       return number >= 0;
    } catch (NumberFormatException e) {
       return false;
    }
}
于 2012-11-08T22:54:15.947 回答
0

如果您想简单地从字符串中读取一个 int,请使用 Integer.parseInt(),尽管这仅在您想查看字符串是否“是”一个 int,而不包含一个 int 时才有效。

您可以使用 Integer.parseInt() 和循环策略的组合来相当容易地查看它是否包含一个 int ,然后只需检查它是否为正。

于 2012-11-08T22:34:54.710 回答
0

你的方法太复杂了。我会保持简单:

if (integer.startsWith("-")) {
    // it's a negative number
}

if (!integer.matches("^\\d+$")) {
    // it's not all-numbers
}

忘记打电话给replaceAll()

于 2012-11-08T22:36:21.457 回答