java - 对象数组 OutOfBoundsException

标签 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本书(第一次出现错误)...

最佳答案

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

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

此问题是 stock 设置为 new Book[stock_max] this.stock_max = size,由于 Java 构造函数和初始化的完成方式。 stock_max 与所有未初始化的 int 一样,从 0 开始,因此 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];
}

关于java - 对象数组 OutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34777454/

相关文章:

c - "error: expected unqualified-id before numeric constant"

OOP:创建电话号码对象或地址对象会有多远?

git - 从 Git 对象恢复文件

java - 改变方法的参数

java - 存储后如何从JAVA中的char输出int

java - lombok AllArgsConstructor 注释中是否包含静态变量?

包含数组的 PHP 常量?

java - 方法描述性名称是为了简单比较还是直接比较?

java - 生成密码字母表

javascript - 错误 : Type '{}' is missing the following properties from type