简体   繁体   English

如果在Java中使用AND运算子

[英]if with AND Operator in java

I have a block of code which uses if statement with AND operator: 我有一块代码,它使用与AND运算符的if语句:

final String NODE_TYPE_LIST = "List";
final String NODE_TYPE_DETAIL = "Detail";
if ((!NODE_TYPE_LIST.equalsIgnoreCase(dataNodeBean.getType())) 
                    && (!NODE_TYPE_DETAIL.equalsIgnoreCase(dataNodeBean.getType()))) {
                throw new InvalidNodeTypeException("Invalid Node type.");
            }

For exampled, if dataNodeBean.getType() returns "List". 例如,如果dataNodeBean.getType()返回“列表”。 According to this link, above code should throw InvalidNodeTypeException only if both expressions in if statement returns true. 根据链接,仅当if语句中的两个表达式都返回true时,以上代码才应引发InvalidNodeTypeException。 But when i'm debugging the program( where dataNodeBean.getType() returns "List" ) i see both expressions being evaluated even though the first expression returns false, as a result the InvalidNodeTypeException(Custom Exception) is thrown. 但是,当我调试程序时(dataNodeBean.getType()返回“ List”),即使第一个表达式返回false,我也会看到两个表达式都被求值,结果抛出了InvalidNodeTypeException(Custom Exception)。 What i expect from this code is to throw an exception when the dataNodeBean.getType() doesn't returns either List or Detail. 我希望这段代码能在dataNodeBean.getType()不返回List或Detail时引发异常。 I don't understand what i'm doing wrong here. 我不明白我在做什么错。

Your code is perfectly fine. 您的代码非常好。 I ran the following test: 我运行了以下测试:

public static void main(String[] args) {
    System.out.println(test("A"));
    System.out.println(test("B"));
    System.out.println(test("C"));
}

private static boolean test(String value) {
    return (!"a".equalsIgnoreCase(value)) && (!"b".equalsIgnoreCase(value));
}

And it returned 它回来了

false
false
true

Just as you'd expect. 正如您所期望的。 I suspect the issue is in the getType method. 我怀疑问题出在getType方法中。 An easy way to confirm is to move your check to a separate method that is passed the result of getType and then write some unit test confirming that it returns true for anything other than "list" or "detail". 一种简单的确认方法是将检查移至传递getType结果的单独方法,然后编写一些单元测试以确认其对除“列表”或“详细信息”之外的任何内容返回true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM