我遇到了ArrayIndexOutofBoundsException错误 - 如何反转数组。

3
我得到了下面程序的输出。此外,我也遇到了一个异常:

以下是需要翻译的内容:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
    at ReverseOrder.main(ReverseOrder.java:15)

为什么会发生这种情况?
public class ReverseOrder {
    public static void main(String[] args)
    {
        int anArray[]={1,2,3,4,5,6};
        int anotherArray[]=new int[6];
        for(int i=5,j=0;i>=0;i--,j++)
        {
            anotherArray[j]=anArray[i];
        }
        //System.out.println(anotherArray.length);
        //System.out.println(anotherArray[2]);
        for(int j=0;j<=anotherArray.length;j++)
        {
            System.out.println(anotherArray[j]);
        }
    }
}
6个回答

3
问题在这里:
 for(int j=0;j<=anotherArray.length;j++)
    {
        System.out.println(anotherArray[j]);
    }

您正在访问数组中的一个位置。这是因为方法 length 给出了数组中元素的数量,而由于数组的第一个位置是 0 而不是 1,您应该在循环结束时使用 anotherArray.length - 1 而不是 anotherArray.length
有两种可能的解决方案:
a) 修改循环为:for(int j=0;j<=anotherArray.length - 1;j++);或者
b) 修改循环为:for(int j=0;j<anotherArray.length;j++)
后者(b)更可取,因为它需要更少的算术运算。

3

改变

for(int j=0;j<=anotherArray.length;j++)

to

for(int j=0;j<anotherArray.length;j++)

因为如果是<=,那么您将会越界。

在Java(和大部分编程语言中),数组的下标是从0开始的。如果你有一个大小为N的数组,则其索引将从0N-1(总大小为N)。


2

变更

<=anotherArray.length

为了

< anotherArray.length

例如,如果数组是:
int arr[] = new int[2];
arr.length; // it will be 2, which is [0] and [1] so you can't go upto <=length,
// that way you will access [2] which is invalid and so the exception

2
for(int j=0;j<anotherArray.length;j++) 

取代

for(int j=0;j<=anotherArray.length;j++) 

因为在Java中,数组是从零开始计数的。


0

当您尝试访问超出数组限制的元素时,会收到ArrayIndexOutOfBoundsException

for(int j=0;j<anotherArray.length;j++) {
    System.out.println(anotherArray[j]);
}

0

你为什么要用这种方式来反转你的数组呢?无论如何。

for(int j=0;j<=anotherArray.length;j++) should change to 

for(int j=0;j<anotherArray.length;j++)

还有这个,很简单。

    int anArray[]={1,2,3,4,5,6};
    int temp=0;
    for (int i=0;i<anArray.length/2;i++){
       temp=anArray[i];
       anArray[i]=anArray[anArray.length-(1+i)];
        anArray[anArray.length-(1+i)]=temp;
    }

现在你的数组已经被反转了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接