0

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. 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.

jl90
  • 629
  • 2
  • 9
  • 23
  • Possible duplicate: http://stackoverflow.com/questions/1128723/in-java-how-can-i-test-if-an-array-contains-a-certain-value – luiges90 Dec 23 '12 at 10:23

4 Answers4

5

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:

boolean allNonZero = true;
for (int entry : array) {
    if (entry == 0) {
        allNonZero = false;
        break;
    }
}
T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
0

EDIT:

boolean isAllNonZero = true;
for(int i = 0; i < array.length; i++) {
    if(myArray[i] == 0) {
        isAllNonZero = false;
        break;
    }
}
Jiri Kremser
  • 11,859
  • 5
  • 42
  • 70
0

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");
}
vels4j
  • 11,026
  • 5
  • 39
  • 57
0

This is (I think) the briefest way to do it:

boolean allNonZero = true;
for (int i : array)
    if (!(allNonZero &= i != 0)) break;
Bohemian
  • 389,931
  • 88
  • 552
  • 692