-1

こんにちは、オブジェクトの配列に問題があります。(オブジェクトの) 配列の長さを 4 に割り当てると、オプション 3 を選択できなくなります (3 を選択すると、プログラムはオプションを要求し続けます。それ以外の場合は、すべてのオプションが正常に機能します)。私ですが、nullポインター例外が発生します(配列には、値が割り当てられていない余分なオブジェクト-nullがあるため)。コンストラクターを呼び出した直後に配列を出力するとします。それは正常に動作します

public static void main(String[] args) 
{
    int menuOption = 0;
    int size = 4;
    BookStore[] book = new BookStore[size];

    //populate the object book for testing purpose
    book[0] = new BookStore("Now", "Me", "Aussie", 2014, 123456, 25.50, 2);
    book[1] = new BookStore("Today", "You", "UK", 1992, 023456, 20.50, 5);
    book[2] = new BookStore("Current", "Me", "Aussie", 2005, 234567, 25.00, 4);
    book[3] = new BookStore("Tomorrow", "You", "UK", 1909, 523456, 20.00, 15);
    //print out the array here, changing the index one by one, I wont have any error
    //E.g. book[0].displayDetails();

    while(menuOption !=1)
    {
        displayMenu();    //display a plain menu
        menuOption = readOption();    //read option from users keyboard

        switch(menuOption)
        {
            ..........
            case 3:
                for(BookStore b: book)
                {
                    b.displayDetails();
                    //if i assign the length of array to 4 does not allow to choose the option 3
                    //if i assign the length of array to 5 null point exception
                }
                break; 
            ........
        }
        ..............
    }
}   


public class BookStore
{
    private String title;
    private String author;
    private String publisher;
    private int year;
    private long isbn;
    private double price;
    private int quantity;

    public BookStore(String bTitle, String bAuthor, String bPublisher, int bYear, 
                     long bIsbn, double bPrice, int bQty)
    {
        title = bTitle;
        author = bAuthor;
        publisher = bPublisher;
        year = bYear;
        isbn = bIsbn;
        price = bPrice;
        quantity = bQty;
    }

    public void displayDetails()
    {
        System.out.println("Title: "+title);
        System.out.println("Author: "+author);
        System.out.println("Publisher: "+publisher);
        System.out.println("Year: "+year);
        System.out.println("Isbn: "+isbn);
        System.out.println("Price: "+price);               
        System.out.println("Quantity: "+quantity);         
        System.out.println("Total Value: "+getTotalValue());
        System.out.println("");  
    }

    public double getTotalValue()
    {
        return (double)quantity * price;
    }
    .........
}
4

1 に答える 1