返回列表 发帖

数组越界的问题

在看入门123,在看数组的时候有这样一个问题
public class Bird06 {
        public static void main(String[] args) {
                int students[][] = new int[1][9];
                int classOne[];
                int classTwo[];
                classOne = students[0];
                classTwo = students[1];
        }
}
以上是看完书后自己试的。
报错: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
        at Bird06.main(Bird06.java:8)
把 int students[][] = new int[1][9]; 改成 int students[][] = new int[2][9]; 就没错了

classTwo = students[1]; classTwo 指向的是 students[1]; 自己理解应该没有越界的问题, 反复看图,也看不出个所以然来, 可以帮忙解释一下为什么吗?
分享到: QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友

你对申明和引用理解有一点偏差。
声明的时候 int[1]  表示数组只有一个元素。这个时候引用时候的下标只能是0

声明的时候 int[2]  表示数组有两个元素。引用下标可以为0、1

二维数组同样的道理。估计这样,你知道代码为什么报错了。

TOP

感谢解释, 现在觉得明白了

TOP

返回列表