Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中的短条件_Java - Fatal编程技术网

java中的短条件

java中的短条件,java,Java,我有4个String变量:a、b、c、d 我检查其中一个是否为null,然后返回false 因此,我: if(a==null | | b==null | | c==null | | d==null)返回false 有没有捷径 (我从java开始)不,您的解决方案是最简单的。-您使用的是非短路或来评估条件,我认为在这种情况下,这是最合适和最简单的 -因此您的解决方案就是它所需要的。如果您的方法如下所示: public boolean foo() { String a = "a", b =

我有4个
String
变量:a、b、c、d

我检查其中一个是否为
null
,然后
返回false

因此,我:

if(a==null | | b==null | | c==null | | d==null)返回false

有没有捷径


(我从java开始)

不,您的解决方案是最简单的。

-您使用的是
非短路或
来评估条件,我认为在这种情况下,这是最合适和最简单的


-因此您的解决方案就是它所需要的。

如果您的方法如下所示:

public boolean foo() {
    String a = "a", b = "b", c = "c", d = "d";
    if(a == null || b == null || c == null || d == null) {
        return false;
    }
    return true;
} 
然后有一种方法可以减少代码。您可以这样做:

public boolean foo() {
    String a = "a", b = "b", c = "c", d = "d";
    return (a != null || b != null || c != null || d != null);
}
但是,如果有更多的字符串要测试,比如说10个,甚至100个,那么需要更少代码的策略就是将字符串放入数组中,并对每个循环使用一个。事实上,以下方法可以处理任何类型的对象,而不仅仅是字符串

如果不知道数组或for each循环是什么,请查看以下内容:


这似乎可以用foreach循环和
字符串来更优雅地表达。它会读得更好,并允许您轻松调试您的语句

// method only returns true if all strings are non-null
public boolean all(String... strings) {
    for(String str : strings) {
        if(null == str) {
           return false;
        }
     }
     return true;
 }
你可以这样称呼它:

return all(a, b, c, d); // will return false if any of these are null, otherwise true.

如果
在这里是多余的,只需使用
返回!(a==null | | b==null | | c==null | | d==null)

如果不是这样,是否要返回
true
?是的,这
公共布尔containsnallobject(Object…objs)
就是我需要的。谢谢
return all(a, b, c, d); // will return false if any of these are null, otherwise true.