有人能回顾一下这篇文章并告诉我问题出在哪里吗?不能传递对数组的引用吗
构造函数还是什么?谢谢..。
class Sort {
int[] input ;
int key=0;
Sort(int[] k){
//Sometimes a method will need to refer to the object that invoked it.
this.input= k ;
}
int[] returnArray() {
for(int i=2 ; i<=input.length ; i++){
key=input[i];
int j=i-1;
while (j>0 && input[j]>key){
input[j+1]=input[j];
j-=1;
}
input[j+1]=key;
}
return input ;
}
}
class InsertionSort{
public static void main (String[] args){
int[] A = {5,8,99,52,22,14,15,1,25,15585,36,244,8,99,25,8};
Sort sort = new Sort(A);
int[] B = sort.returnArray();
for (int i=0 ; i<B.length ; i++){
System.out.println("the array after sorting : ");
System.out.print( B[i] + " " );
}
}
}..。
这就是whatsitssname的确切内容:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 16 out of bounds for length 16<br/>
at Sort.returnArray(InsertionSort.java:10)<br/>
at InsertionSort.main(InsertionSort.java:25)<br/>发布于 2020-05-20 14:13:20
您的代码试图访问数组的索引16,但该数组的最后一个索引是15,因为它有16个元素从索引0开始。
这就是问题发生的地方:
for(int i=2 ; i<=input.length ; i++){
// when i is input.length (16), you'll be accessing an out of bounds index
// wich will throw a java.lang.ArrayIndexOutOfBoundsException
key=input[i];因为i不应该到达input.length,所以您需要使用<而不是<=。
发布于 2020-05-20 14:13:54
这个错误在你的for循环中。如果你想从第三个元素迭代到最后一个元素,它应该是。
for(int i=2 ; i<input.length ; i++){如果你想从第二个元素迭代到最后一个元素,如果应该是
for(int i=1 ; i<input.length ; i++){您现在所做的基本上是尝试访问长度为len的数组的ilen。它并不存在
https://stackoverflow.com/questions/61906232
复制相似问题