Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.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中用数组简化if语句_Java_Arrays_If Statement - Fatal编程技术网

java中用数组简化if语句

java中用数组简化if语句,java,arrays,if-statement,Java,Arrays,If Statement,我有一个if语句,如下所示,我正在检查count数组中的所有值是否都等于零 if (count[1] == 0 && count[2] == 0 && count[3] == 0 && count[4] == 0 && count[5] == 0 && count[6] == 0) { } 有没有办法简化这句话?另外,请注意,我不想检查计数[0]您可以使用and 这将包括count[0],要排除count[0]

我有一个if语句,如下所示,我正在检查
count
数组中的所有值是否都等于零

if (count[1] == 0 && count[2] == 0 && count[3] == 0 && count[4] == 0 
&& count[5] == 0 && count[6] == 0) {

}
有没有办法简化这句话?另外,请注意,我不想检查计数[0]

您可以使用and

这将包括
count[0]
,要排除
count[0]
,您可以这样做

if (IntStream.rangeOf(1, count.length).allMatch(x -> count[x] == 0)) {

}
或者(谢谢)

你可以使用and

这将包括
count[0]
,要排除
count[0]
,您可以这样做

if (IntStream.rangeOf(1, count.length).allMatch(x -> count[x] == 0)) {

}
或者(谢谢)


一种可能的解决方案是使用一个简单的for循环来迭代
count
数组,并检查数组中包含的元素的值,以确定它们是否具有零值

public boolean isAllZero(int[] array){
   for(int i = 1; i < array.length; i++){
      if(array[i] != 0){
         return false;
      }
   } 
   return true;
}
公共布尔值isAllZero(int[]数组){
for(int i=1;i
一种可能的解决方案是使用一个简单的for循环来迭代
计数
数组,并检查数组中包含的元素的值,以确定它们的值是否为零

public boolean isAllZero(int[] array){
   for(int i = 1; i < array.length; i++){
      if(array[i] != 0){
         return false;
      }
   } 
   return true;
}
公共布尔值isAllZero(int[]数组){
for(int i=1;i

 boolean  isAllZero = Arrays.asList(myArray).stream().allMatch(val -> val == 0);
在Java8中

 boolean  isAllZero = Arrays.asList(myArray).stream().allMatch(val -> val == 0);

您可以使用循环(在您的案例中从1开始)来设置布尔结果变量。您可以使用循环(在您的案例中从1开始)来设置布尔结果变量。我倾向于编写较短的
IntStream.of(count)。skip(1)。allMatch(x->x==0)
我倾向于编写较短的
IntStream.of(count)。skip(1)。allMatch(x->x==0)