Skip to content
Advertisement

Validating elements of a 2D array

My code for making sure an element isn’t over 100 or less than 0 is:

boolean test = true;
for (int i = 0; i < inArray.length; i++) {
    for (int j = 0; j < inArray[0].length; j++) {
        if (inArray[i][j] <= 1 && inArray[i][j] >= 100) {
            test = false;
        }
    }
}
return test;

Except no matter what the input is the answer is always true

My input array is

{12, 1331, 23, 5, 1, 3},
{22, 23, 231, 21312, 1, 3},
{23, 31, 343, 3432, 1, 3},
{42, 12, 5454, 1212, 3, 9}

test should = false if I input this no?

College rules mean I cannot use break; or return anywhere other than the end of the sub module.

Answer

You have three problems here, two of which are critical. First, if you want to iterate over each subarray, test its length, not the length of array[0] every time. And second, integers cannot be less than 2 and over 99, so your conditional (inArray[i][j] <= 1 && inArray[i][j] >= 100) is never going to fire.

However, there’s more at play here: if your test is purely to see whether your 2d array is valid, don’t do more work than necessary. You can literally stop once you find a single bad element. Now, we could do that by adding a check to your for conditionals. E.g. we can rename your variable to valid (because you should name variables after what they represent), and then we can update your outer loop to for(int i=0; valid && i < arr.length; i++) { ... } with the corresponding valid && ... in the inner loop, too, but we’re not going to. This code “does a thing” (namely it “tests for element validity” for any array-of-arrays), and code that “does a thing” should be in its own method, with a method name that describes what it does. And this makes “not doing any of the work we don’t need to do” much, much easier: we just exit the function when we know we’ve done enough work to produce an answer.

So let’s do that:

// 1st fix: this code "does soemthing". Do that as a method.
public boolean testForValidContent(int[][] arr) {
  // We don't need a variable to track things: because we're
  // returning a value, we can simply return the right value
  // at the moment we return.

  for(int i = 0; i < arr.length; i++) {
    for(int j = 0; j < arr[i].length; j++) { // 2nd fix: check the right array's length
      if(arri][j] <= 1 || arr[i][j] >= 100) { // 3th fix: OR, not AND

        // At this point we know the array is not valid, so there
        // is no point in running even a single thing more:
        return false;

      }
    }
  }

  // We checked the entire array, and everything's valid:
  return true;
}
Advertisement