简体   繁体   English

检查 java 中的条件导致错误

[英]checking the condition in java leading to error

I have the below piece of code in which under if condition I am getting the sonar findings that is Strings literals should be placed on the left side when checking for equality.我有下面的一段代码,在 if 条件下,我得到的声纳结果是字符串文字,在检查相等性时应该放在左侧。 Please advise how to overcome this.请告知如何克服这个问题。

final String aviid = avcMaster.getAVMaster().getAviiId();
if ((!aviid.equals("44")) || (!aviid.equals("55"))) { // ** Sonar Issue **//
    final String defaultAiId = "88";
    deviceElement.setAttribute("avi", defaultAiId);
}
else{
    deviceElement.setAttribute("avi", aviid);
}

Comparison between String variable and String literal String变量和String字面量的比较

  • calling the method on the variable: if the variable is null you'll get a NullPointerException在变量上调用方法:如果变量是 null 你会得到一个NullPointerException

     aviid.equals("44")
  • calling the method on the literal: you can't get a NPE and you'll have false in case the variable holds null在文字上调用该方法:如果变量包含null ,您将无法获得 NPE,并且您将获得false

     "44".equals(aviid)

Sonar warns you because for it, it's better to get false than NPE , but the code is your choice. Sonar 会警告您,因为对于它来说,获得 false 比NPE更好,但代码是您的选择。


Also your test is wrong because it'll always be true, as you can't have 44 and 55 at the same time, one of them will be true, you surely meant && , also you'd better do it the other way you wouldn't need the negation.另外,您的测试是错误的,因为它始终是正确的,因为您不能同时拥有 44 和 55,其中一个是正确的,您肯定是指&& ,而且您最好以另一种方式进行不需要否定。

if ((!aviid.equals("44")) && (!aviid.equals("55"))) { 

And to do it shorter (from comments)并且做得更短(来自评论)

deviceElement.setAttribute("avi", aviid.matches("44|55") ? aviid : "88");

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

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