简体   繁体   English

确保数组中的所有元素都不为零

[英]Making sure that all elements in array is not zero

How can I code this in a simpler way? 如何以更简单的方式编写代码?

for(int i=0; i<array.length; i++)
{
    if(myArray[i] == 0)
    {
        myBoolean = false;
        break;
    }
    else if(myArray[0] != 0 && myArray[1] != 0 && myArray[2] != 0)
    //may continue depending on array length
    {
        myBoolean = true;
    }
}

What I currently have is a "if else statement" that if in my array, just an element is not zero it will change my boolean to true. 我目前拥有的是一个“ if else语句”,如果在我的数组中,只是一个元素不为零,它将把我的布尔值更改为true。 But what I need is to make sure that all elements in the array is not zero then it will change the boolean to true. 但是我需要确保数组中的所有元素都不为零,然后它将布尔值更改为true。

You're overcomplicating it: :-) (I seem to have misread the question earlier, but I've fixed the answer now.) 您使它过于复杂::-) (我似乎早先已经错读了问题,但是现在我已经确定了答案。)

boolean allNonZero = true;
for (int i = 0; allNonZero && i < array.length; ++i) {
    if (array[i] == 0) {
        allNonZero = false;
    }
}

or even 甚至

boolean allNonZero = true;
for (int i = 0; allNonZero && i < array.length; ++i) {
    allNonZero = array[i] == 0;
}

or using the enhanced for loop: 或使用增强的for循环:

boolean allNonZero = true;
for (int entry : array) {
    if (entry == 0) {
        allNonZero = false;
        break;
    }
}

EDIT: 编辑:

boolean isAllNonZero = true;
for(int i = 0; i < array.length; i++) {
    if(myArray[i] == 0) {
        isAllNonZero = false;
        break;
    }
}

Just check pretense of zero. 只是假装零。

boolean isAllNonZero = true;
for(int i=0; i<array.length; i++)
{
    if(myArray[i] == 0)
    {
        isAllNonZero = false;
        break;
    }
}
if(!isAllNonZero) {
  System.out.println("Array Contains zero value");
}

Even more

int count = 0 ;
for(int i=0; i<array.length; i++)
{
    if(myArray[i] == 0)
    {
        count++;
    }
}
if(count>0){
  System.out.println("Array Contains "+count+" zeros");
}

This is (I think) the briefest way to do it: (我认为)这是最简单的方法:

boolean allNonZero = true;
for (int i : array)
    if (!(allNonZero &= i != 0)) break;

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

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