如何摆脱错误ArrayIndexOutOfBound异常?

时间:2014-12-23 12:59:08

标签: java exception

public class Main {

public static void main(String[] args) {

    int[] numbers = {1, 2, 3}; // it gives me arrayindexoutofboundexception

    int length = numbers[3];

    char[] chars = new char[length];

    chars[numbers.length + 4] = 'y';

    System.out.println("Done!");
}

}

如何删除数组索引超出绑定的异常。

2 个答案:

答案 0 :(得分:4)

当您的数组只有3个元素,其索引为0,1和2时,不要访问numbers[3];

在确保这是chars[numbers.length + 4]数组的有效索引之前,请不要访问chars

答案 1 :(得分:0)

变化:

int length = numbers[3]; 

要:

int length = numbers[2];
相关问题