熟悉Netbeans的人:为什么会这样?错误不是真的错误吗?

时间:2013-10-31 01:26:48

标签: java netbeans ide

写这样简单的东西时:

import java.util.Scanner;
public class Practice {  
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); 
        System.out.println("Please enter array size: ");
        int x = sc.nextInt();
        int [] anArray;
        int index = 100;
        anArray = new int[x];
        for (int i=0; i<=x; i++){
            anArray[i] = index;
            index += 100;
            System.out.println ("Element at index "+ i + ": " + anArray[i]);
        }

    }

}

Netbeans正确编译并运行代码,但输出最终看起来像这样:

run:
Please enter array size: 
12
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
Element at index 10: 1100
Element at index 11: 1200
   at Practice.main(Practice.java:21)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)

这对我来说似乎不错..为什么在代码中途抛出异常?然后在最后完成?

它指向第21行:     anArray [i] = index;

老实说,这不是一个大问题..我只是在玩游戏并回顾一些Java的基础知识(已经有一段时间了......)而且例外情况让我觉得我做错了什么但后来我就是不确定我实际上是因为它看起来像我的意图。

谢谢!

1 个答案:

答案 0 :(得分:2)

更改for语句:

for (int i=0; i<x; i++){ // Change <= to <
        anArray[i] = index;
        index += 100;
        System.out.println ("Element at index "+ i + ": " + anArray[i]);
    }

如果使用length = 12创建数组,则可以通过以下方式访问它:

anArray[0]
anArray[1]
...
anArray[11]

但是你要访问它anArray[12],所以它会抛出错误。