gpt4 book ai didi

java - java中的比较问题[.equals()]

转载 作者:行者123 更新时间:2023-12-01 18:58:04 24 4
gpt4 key购买 nike

我试图确定一个字符串是否包含正整数。我的代码是:

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....

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

最佳答案

由于您在第一个 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。如果有效,则测试其是否小于0。它将更加容易和可读。

关于java - java中的比较问题[.equals()],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13299009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com