Java数组索引超出范围4

Java数组索引超出范围4

问题描述:

我是Java的新手,正在下面运行良好的代码下运行,但是我得到了数组索引超出范围的异常。

I am new to Java and was running below code which runs fine but I get an array index out of bound exception. Can someone please help understand why am I getting this exception?

public class array {
    public static void main (String[] args)
    {
    int[] b = {1,2,3,4};
    array ar = new array();
    ar.process(b);
    }
    public int process (int[] a)
    {
    int i;
    System.out.println("Length is: " +a.length);
    for(i = 0; i < a.length ; i++) {
    System.out.println("A is : " + a[i] + "  I is" +i);        
    }
    return a[i];
    }        
    }

Exception

Length is: 4
A is : 1  I is0
A is : 2  I is1
A is : 3  I is2
A is : 4  I is3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
        at array.process(array.java:17)
        at array.main(array.java:7)


问题是这一行:

return a[i];

因为它在 for 循环之外并且我已经变成4。

Since it is outside for loop and i has become 4.

您可以做到:

return a[i-1];

对其进行修复,但是您需要弄清楚为什么要返回数组的最后一个元素作为return值。

to fix it, but you need to clarify why you're returning last element of an array as return value.