Java数组索引超出范围4 [英] Java array index out of bound 4

查看:81
本文介绍了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.

这篇关于Java数组索引超出范围4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆