猿问

.Array Index Out Of Bounds Exception in for loop

Eclipse IDE 抱怨使用/访问书籍数组的 for 循环越界。它抱怨的第 (19) 行是: if (books[x] == null) {

我不相信这是它抱怨的问题,因为我已经用许多不同的东西替换了它,但它仍然在抱怨。一行是 for 循环的第一行 for (int x = 0; x < capacity ; ++x)

我也三重检查了条件是否正确,应该是。容量为 5,这意味着对象位置数组将位于 0、1、2、3、4,因此根据我对数组的了解,从 0 开始 x 应该是正确的。

库类(带循环的)

    package exercises;


    public class Library {

        private int capacity;

        private Book[] books = new Book[capacity];

        public Library(int capacity) {

            if (capacity > 1) {

                this.capacity = capacity;

            }

            else {

                this.capacity = 4;

            }

        }

        public boolean addBook(Book book) {

            int freeLocation = -1;

            @SuppressWarnings("unused")

            int notFreeLocation = -1;

            for (int x = 0; x < capacity ; ++x) {

                if (books[x] == null) { /*this is line 19*/

                    freeLocation = x;

                }

                else {

                    notFreeLocation = x;

                }

            }


            if (freeLocation == -1) {

                return false;

            }

            else {

                books[freeLocation] = book;

                return true;

            }

        }

我在 exercises.Library.addBook(Library.java:19) 和 exercises.LibraryApp.main(LibraryApp.java:8) 处收到错误“线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:0”


ibeautiful
浏览 125回答 1
1回答

慕桂英3389331

当这完成时Library:private int capacity;private Book[] books = new Book[capacity];super()构造函数中的代码尚未运行(这些初始化在最开始 [或在子类之后] 插入到构造函数中)。所以capacity有它的默认值,0。后来你分配给capacity,但为时已晚。反而:public class Library {&nbsp; &nbsp; private int capacity;&nbsp; &nbsp; private Book[] books;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// *** Don't initialize it here&nbsp; &nbsp; public Library(int capacity) {&nbsp; &nbsp; &nbsp; &nbsp; if (capacity > 1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.capacity = capacity;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.capacity = 4;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; this.books = new Book[this.capacity]; // *** Initialize it here&nbsp; &nbsp; }但是这里还有另一个有用的东西要学。在遍历数组或类似数组时,使用数组的大小知识,而不是其他信息源 ( capacity)。所以:for (int x = 0; x < this.books.length ; ++x) {// -----------------^^^^^^^^^^^^^^^^^坚持真相的主要来源。capacity:-)(事实上,您可能根本不需要您的实例成员。)
随时随地看视频慕课网APP

相关分类

Java
我要回答