嗨,我的对象数组有一些问题。如果我将数组(对象)的长度分配给 4,它不允许我选择选项 3(当我选择 3 时程序会一直询问该选项。否则所有选项都可以正常工作),如果我将它分配给 5 它允许我,但我得到空指针异常(因为数组将有一个额外的对象,没有分配给它的值 - 空)。如果我在调用构造函数之后打印出数组。它工作正常
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;
}
.........
}