-1

I'm trying to write a function that cycles through an integer array looking for zeros. It looks like this:

def fullIntArray(arr:Array[Int]): Boolean = {

  var counter = 0;
  for(a <- 1 to arr.length by 1){
    if(arr(a) != 0){
      counter += 1;
    }
  }

  if(counter == arr.length){
    return true;
  }else{
    return false;
  }
}

I'm getting an ArrayIndexOutOfBoundsException from

arr(a)

Can anyone explain why, or what I should do instead?

Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54
  • Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Krease Oct 17 '17 at 16:58

1 Answers1

4

You're getting the exception because the index of the first element in an Array is zero, not one. The following works (the by 1 is fine but unnecessary):

for (a <- 0 to arr.length - 1 by 1) {
  if (arr(a) != 0) {
    counter += 1
  }
}

And so does the following, as @puhlen suggested:

for (a <- 0 until arr.length) {
  ...
}

However, a better way to implement your function is:

def fullIntArray(arr: Array[Int]): Boolean = arr.forall(_ != 0)
Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54