关于java:对象数组OutOfBoundsException

Array of Objects OutOfBoundsException

本问题已经有最佳答案,请猛点这里访问。

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

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

我的整个代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
2
3
4
5
6
7
private int stock_max;
Book[] stock = new Book[stock_max];
private int book_counter;

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

这个问题是EDCOX1〔0〕在EDCOX1Ω2Ω线之前被设置为EDCOX1〔1〕,这是由于Java构造函数和初始化的方式。与所有未初始化的ints一样,stock_max0开始,因此stock被设置为空数组。要解决此问题,只需在构造函数内移动初始化:

1
2
3
4
5
6
7
8
private int stock_max;
Book[] stock;
private int book_counter;

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