0

i'm (relative) new to java, i have some (minor) understanding of Arrays and Classes/Objects etc. But i can't find the solution to this Errors.

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

My whole Code:

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]);
}

}

I know that the ArrayIndexOutOfBoundsException means that it tries to make something at an index that doesnt exist. But i set the size of the bookshop to 10, and then add only 4 books to it (Error occurs at the first)...

Mechamod
  • 21
  • 8

1 Answers1

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

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

This issue is that stock is set to new Book[stock_max] before the line this.stock_max = size, due to the way Java constructors and initialization is done. stock_max, like all uninitialized ints, starts at 0, so stock is set to an empty array. To fix this, just move the initialization inside the constructor:

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

public Bookshop(int size){
    this.stock_max = size;
    this.stock = new Book[stock_max];
}
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413