2014-12-23 86 views
1

公共类主要{如何摆脱ArrayIndexOutOfBound异常的错误?

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!"); 
} 

}

如何删除数组索引出界异常。

回答

4

不要访问numbers[3];当你的阵列只有3个要素,其指数是0,1和2

而且要确保这是chars阵列的有效索引前不会访问chars[numbers.length + 4]

+0

非常感谢,它帮助。 如果我试图捕捉异常,那么它会毫无例外地编译,但没有输出,你能解释一下,谢谢? –

+0

@KedarKholiya别抓住这个例外。你应该首先避免它。 – Eran

0

变化:

int length = numbers[3]; 

要:

int length = numbers[2]; 
+0

完成,但没有help.giving运行时错误 –

+0

@KedarKholiya - 检查*伊兰的*答案。行'chars [numbers.length + 4] ='y';'是*自杀*。 – TheLostMind

+0

谢谢..现在它工作。 –