2

I want my program to check whether every element in the entire int[] array is non-zero.

What I currently have:

for(int i=0; i<myArray.length; i++)
{
  if(myArray[i] == 0)
  {
    completed = false;
  }
  else
  {
    completed = true;
  }
}

But the loop keeps doing else statement, if only one array in the middle is non-zero and won't check the rest of the array.

1

5 Answers 5

4

You need to have it break out of the for loop once you've found a 0:

if(myArray[i] == 0)
  {
    completed = false;
    break;
  }

This way, if you find a non-0 element later, you won't falsely set completed back to true.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use a break statement to break the loop on first occurrence of a zero value as:

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

 if(!completed){
     //array has zero values
 }

Other important pointers:

  1. Arrays.binarySearch(): works only on sorted array so not useful in your case.

    Searches the specified array of bytes for the specified value using the binary search algorithm. The array must be sorted (as by the sort(byte[]) method) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.

  2. indexOf method internally does the same loop and comparison. So I don't see much difference in your original pattern and new syntax. Though it may make your code look compact.

1 Comment

+1 Arrays.binarySearch() works only on sorted array so not useful in your case.
0

You can put break; statement after finding the first 0 element, so that it will jump out the loop.

Comments

0

There is no need to loop through each elements: JSBIN Demo

Use IndexOf();

var myArray = [1,2,1,3];
var completed = myArray.indexOf(0) != -1

1 Comment

Why not just var completed = myArray.indexOf(0) != -1?
-1

Alternately, you could do

var completed = true;
for(int i=0; i<myArray.length; i++)
{
   if(myArray[i] == 0)
   {
       completed = false;
   }
}

Which would do the same.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.