【问题标题】:Sequence of or and and in if block not working correctlyif 块中的 or 和 and 的顺序无法正常工作
【发布时间】:2021-06-04 03:58:05
【问题描述】:
 CCMT c = new CCMT();
 c.ccd = null;
Optional<String> cType = Optional.ofNullable(ccmtRequest).map(CCMT::getCcd).map(MOEH::getDestCtry);         

System.out.println(cType.isPresent()); // false
    
if(cType.isPresent() && cType.get().equalsIgnoreCase("CCMT") || cType.get().equalsIgnoreCase("CCWC")) {
  System.out.println("wfegr");
}

错误:异常NoSuchElementException

为什么 cType.get() 语句被执行,即使首先 条件是 false 本身?

【问题讨论】:

  • 正在正常工作。你只需要在正确的地方使用括号

标签: java if-statement operators relational


【解决方案1】:

这是由于operator precedence。 写A &amp;&amp; B || C和写(A &amp;&amp; B) || C是一样的。

因此,在您的情况下,您需要在 || 运算符周围添加括号:

if (cType.isPresent() && (cType.get().equalsIgnoreCase("CCMT") || cType.get().equalsIgnoreCase("CCWC"))) {
    System.out.println("wfegr");
}

但使用Optional API 的更多方法可能更合适:

cType
    .filter(t -> t.equalsIgnoreCase("CCMT") || t.equalsIgnoreCase("CCWC"))
    .ifPresent(t -> System.out.println("wfegr"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多