public class TestArray {
public static void main(String args[]) {
int a[] = new int[args.length];
for(int i=0; i<=args.length; i++) {
a[i] = Integer.parseInt(args[i]);
System.out.print(a[i] + " ");
}
}
}为什么我这样写会抛出异常:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:10
at TestArray.main(TestArray.java:6)
public static void main(String args[]) {
int a[] = new int[args.length];
for(int i=0; i<=args.length; i++) {
a[i] = Integer.parseInt(args[i]);
System.out.print(a[i] + " ");
}
}
}为什么我这样写会抛出异常:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:10
at TestArray.main(TestArray.java:6)
public static void main(String args[]) {
int a[] = new int[args.length];
for(int i=0; i<args.length; i++) {
a[i] = Integer.parseInt(args[i]);
System.out.print(a[i] + " ");
}
}
}
for(int i=0; i<=args.length; i++) 改成:for(int i=0; i<args.length; i++)。数组的下标范围为:[0, length - 1]共length个元素,你用[0, length]就变成length + 1个了,最后一个array[length]自然就会越界了。