无法确定越界异常的位置

Having trouble figuring out where the out of bounds exception is at

我正在开发一个项目,我们正在创建一个 'efficient shuffling' 方法,该方法接受一个数组并随机排列其中的值的位置。但是,我遇到了越界异常运行时错误,我不确定是什么原因造成的。

public static void selectionShuffle(int[] values) {
   for(int k = values.length; k > 0; k--) {
     int[] temp = new int[k];
     double rand = Math.floor(Math.random() * k);
     int r = (int) rand;
     temp[r] = values[r];
     values[r] = values[k];  //here is where the outofbounds error resides
     values[k] = values[r];
   }
 }

这是方法,这是 运行 它的代码。这是给我的,不应更改。

 private static final int SHUFFLE_COUNT = 1;
 private static final int VALUE_COUNT = 4;

 public static void main(String[] args) {
  System.out.println("Results of " + SHUFFLE_COUNT +
         " consecutive perfect shuffles:");
  int[] values2 = new int[VALUE_COUNT];
  for (int i = 0; i < values2.length; i++) {
   values2[i] = i;
   }
  for (int j = 1; j <= SHUFFLE_COUNT; j++) {
   selectionShuffle(values2);    //error is referenced here, when the method is called
   System.out.print("  " + j + ":");
   for (int k = 0; k < values2.length; k++) {
    System.out.print(" " + values2[k]);
   }
   System.out.println();
  }
  System.out.println();
 }

这里的代码有点分段,只是为了更容易阅读。

for(int k = values.length

开始 k 作为值的长度,然后

values[r] = values[k];  //here is where the outofbounds error resides

导致异常,因为 Java 数组是零索引的。

您可以通过将 for 循环更改为

来解决此问题
for(int k = values.length-1; k >= 0; k--)