当写这样简单的东西时:
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 的一些基础知识(已经有一段时间了......),例外是让我觉得我做错了什么,但我不确定我实际上是因为它似乎按我的意图工作。
谢谢!