ArrayIndexOutOfBounds异常

时间:2012-07-01 03:32:41

标签: java exception

public class Repetition {
  public static void main (String[]a){
    int[] x;
    x = new int[10];
    int i;
    int n=0;
      for (i=0;i<x.length;i++){
        n++;
        x[i]=n;
        System.out.print(x[i] + " ");
      }
    i=0;
    while (x[i]<x[10]){
      System.out.println(x[i]);
      i++;
   }
}

运行程序后,会显示以下错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Repetition.main(Repetition.java:14)
1 2 3 4 5 6 7 8 9 10 Java Result: 1

实际上,我还是这种语言的新手。我正在尝试创建一个程序,将值分配给10个数组并显示它们并从第一个数组开始再次显示。

我希望输出如下:

1 2 3 4 5 6 7 8 9 10

1 2 3 4 5 6 7 8 9 10

1 个答案:

答案 0 :(得分:6)

ArrayIndexOutOfBoundsException表示您尝试将索引用于数组,并且该索引不存在。例如,如果数组中的最后一个有效索引是9并且您使用10,那么您将收到此错误。

这行代码是问题(错误消息告诉你行号):

while (x[i]<x[10]){

x是一个长度为10的数组,这意味着它的索引从0(零)到9. x[10]不存在,因此您得到错误。

相关问题