Error: IndexOutOfBoundsException while calculation sum of array

Error: IndexOutOfBoundsException while calculation sum of 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 打印错误:

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)

https://docs.oracle.com/javase/7/docs/api/java/lang/IndexOutOfBoundsException.html中我发现:

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.

我的理解是 index 超出了 myArray.size 的范围。这是为什么?

for (number in myArray) 循环的目的是什么?这是这个错误的根源。此循环的第一次迭代后 index 变量等于 myArray.size。在下一次迭代中,您会收到此异常,因为在 do-while 循环中,主体首先执行,然后检查条件。

顺便说一句,在 kotlin 中为数组定义了一个很好的 sum 方法。

您正在迭代数组两次,一次使用 for 循环,一次使用内部 do-while 循环。由于 index 是在两个循环之外定义的,因此它被分配给 myArray.size。尝试访问索引大于 size-1 的数组元素将抛出 ArrayIndexOutOfBoundsException.

如何调试

对于初学者,开始在代码中添加 print 语句以查看特定时刻的值。如果您正在使用任何 IDE 之类的 Intellij,请开始使用断点来检查值是否为运行时

这里有几种解决问题的方法。

只使用 for 循环

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

或使用 while 循环

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

或者使用Kotlin已有的函数求和

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

一些额外的(不必要的)选项

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 }
}