Art
Art

Reputation: 17

Error: IndexOutOfBoundsException while calculation sum of array

I'm trying to calculate sum of the array.

fun main (args: Array<String>) {
   var myArray = arrayOf(66, 23, 5, 46, 76, 56, 3, 277, 6, 9494, 574, 34, 23, 6467, 13, 64, 75, 634, 234, 2314)
   println("The sum of the array is: ${getSumArray(myArray)}")
}
   fun getSumArray(myArray: Array<Int>): Int {
      var total = 0
      var index = 0
      for (number in myArray) {
         do {
            total = total + myArray[index]
            index++
         } while (index < myArray.size)
      }
      return total
   }

IDE prints an error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20 at ExercisesKt.getSumArray(Exercises.kt:19) at ExercisesKt.main(Exercises.kt:12)

In https://docs.oracle.com/javase/7/docs/api/java/lang/IndexOutOfBoundsException.html I found:

public class IndexOutOfBoundsException extends RuntimeException Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.

How I understand it means that index is out of range of myArray.size. Why is that?

Upvotes: 0

Views: 116

Answers (2)

sidgate
sidgate

Reputation: 15244

You are iterating the array twice, once using the for loop and inner do-while loop. As the index is defined outside both the loops, it gets assigned to myArray.size. trying to access array element with index larger than size-1 will throw ArrayIndexOutOfBoundsException.

How to debug

For beginners, start adding print statements within the code to see what the value is at particular moment. If you are using any IDE like Intellij, start using breakpoint to check the values are runtime

Here are few alternatives to fix the issue.

Use just the for loop

fun getSumArray(myArray: Array<Int>): Int {
  var total = 0
  for (number in myArray) {
    total += number
  }
  return total
}

or use the while loop

fun getSumArray(myArray: Array<Int>): Int {
  var total = 0
  var index = 0
    do {
      total = total + myArray[index]
      index++
    } while (index < myArray.size)
  return total
}

Or use Kotlin's existing function to get the sum

fun getSumArray(myArray: Array<Int>): Int {
  return myArray.sum()
}

Some additional (unnecessary) options

fun getSumArray(myArray: Array<Int>): Int {
  var total = 0
  myArray.forEach {
    total+=it
  }
  return total
}

.

fun getSumArray(myArray: Array<Int>): Int {
  return myArray.reduce { acc, n -> acc + n }
}

Upvotes: 1

What is the purpose of for (number in myArray) loop? It is the source of this error. After first iteration of this loop index variable is equal to myArray.size. On the next iteration you get this exception because in do-while loops the body executes first and then condition is checked.

By the way, there is a nice sum method defined for arrays in kotlin.

Upvotes: 0

Related Questions