对象数组OutOfBoundsException

时间:2016-01-13 21:33:08

标签: java arrays object

我(相对)是java的新手,我对数组和类/对象等有一些(次要的)理解。但我找不到这个错误的解决方案。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at books$Bookshop.addBook(books.java:42)
at books.main(books.java:57)

我的整个代码:

public class books {

static class Book{
    private double price;
    private String title;
    private String isbn;

    public Book(double price, String title, String isbn){
        this.price = price;
        this.title = title;
        this.isbn = isbn;
    }

    public Book makeBook(double price, String title, String isbn){
        Book new_book = new Book(price, title, isbn);
        return new_book;
    }

    public String toString(){
        String string = this.title + ", " + this.isbn + ", " + this.price;
        return string;
    }
}

static class Bookshop{
    private int stock_max;
    Book[] stock = new Book[stock_max];
    private int book_counter;

    public Bookshop(int size){
        this.stock_max = size;
    }

    public void printBooks(){
        for(int i=0; i<stock.length; i++){
            System.out.println(stock[i].toString());
        }
    }

    public void addBook(double p, String t, String i){
        this.stock[book_counter] = new Book(p,t,i);
    }

    public void searchBook(String title){
        for(int i=0; i<stock.length; i++){
            if(title.equals(stock[i].title)){
                System.out.println("Book in Stock");
            }
        }
    }
}


public static void main(String[] args) {
    Bookshop shop = new Bookshop(10);
    shop.addBook(29.90, "title", "24578");
    shop.addBook(19.59, "second", "12345");
    shop.addBook(69.99, "third title", "47523");
    shop.addBook(4.99, "title 4", "98789");
    shop.printBooks();

    shop.searchBook(args[0]);
}

}

我知道ArrayIndexOutOfBoundsException意味着它试图在一个不存在的索引上创建一些东西。但我将书店的大小设置为10,然后只添加4本书(第一次出现错误)......

1 个答案:

答案 0 :(得分:3)

private int stock_max;
Book[] stock = new Book[stock_max];
private int book_counter;

public Bookshop(int size){
    this.stock_max = size;
}

由于Java构造函数和初始化的完成方式,此问题是stock在行new Book[stock_max]之前设置为this.stock_max = size 。与所有未初始化的stock_max一样,int0开始,因此stock设置为空数组。要解决这个问题,只需在构造函数中移动初始化:

private int stock_max;
Book[] stock;
private int book_counter;

public Bookshop(int size){
    this.stock_max = size;
    this.stock = new Book[stock_max];
}