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:

JavaScript

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

My input array is

JavaScript

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.

Advertisement

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:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement