Java添加按钮GUI增长阵列

时间:2014-02-09 19:38:06

标签: java arrays user-interface add

我正在尝试在GUI界面中创建一个添加按钮,但我需要这个“添加按钮”来提示用户将数据输入到提供的字段中,并且应用程序还会放置所有现有库存随着新书创建成一个新的阵列。我目前得到的错误是在编译后尝试运行它。

"Exception in thread "main" java.lang.NullPointerException
at Bookstore.calculateInventoryTotal(Bookstore.java:198)
at Bookstore.main(Bookstore.java:232)"

请注意,由于此异常,GUI根本无法启动。 我已粘贴下面的所有代码,感谢您抽出时间看看这个!

import java.util.Arrays;
import java.text.NumberFormat;
import java.util.Locale;
import java.text.DecimalFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;





// Begin class Book
class Book
{
private String isbn;
private String title;
private String authorName;
private int yearPublished;
private String publisherName;
private double price;

NumberFormat usCurrency = NumberFormat.getCurrencyInstance(Locale.US);

public Book (String isbn, String title, String authorName, int yearPublished, String publisherName, double price)
{
    this.isbn = isbn;
    this.title = title;
    this.authorName = authorName;
    this.yearPublished = yearPublished;
    this.publisherName = publisherName;
    this.price = price;
}


///////////////////////////////////////////////
public void setISBN (String ISBN) //set ISBN
{
    this.isbn = ISBN;
}
public String getISBN () //get ISBN
{
    return isbn;
}
//////////////////////////////////////////////
public void setTitle (String Title) //set Title
{
    this.title = Title;
}
public String getTitle () //get Title
{
    return title;
}
///////////////////////////////////////////////
public void setAuthorName (String AuthorName) //set AuthorName
{ 
    this.authorName = AuthorName;
}
public String getAuthorName () //get AuthorName
{
    return authorName;
}
///////////////////////////////////////////////
public void setYearPublished (int YearPublished)//set YearPublished
{
    this.yearPublished = YearPublished;
}
public int getYearPublished () //get YearPublished
{
    return yearPublished;
}
///////////////////////////////////////////////
public void setPublisherName (String PublisherName)
{
    this.publisherName = PublisherName;
}
public String getPublisherName ()
{
    return publisherName;
}
///////////////////////////////////////////////
public void setPrice (double Price)
{
    this.price = Price;
}
public double getPrice ()
{
    return price;
}


//toString method
public String toString ()
{
    return "ISBN:" + "\t\t\t" + isbn + "\n" +
           "Title:" + "\t\t\t" + title + "\n" +
           "Author's Name:" + "\t \t" + authorName + "\n" +
           "Year Published:" + "\t \t" + yearPublished + "\n" +
           "Publisher's Name:" + "\t\t" + publisherName + "\n" +
           "Price" + "\t\t\t" + usCurrency.format(price) + "\n";
}
} // end class Book


//Begin class EBook
class EBook extends Book
{
private String webSite;


// constructor
public EBook (String isbn, String title, String authorName, int yearPublished, String publisherName, double price, String webSite)
{
    super(isbn, title, authorName, yearPublished, publisherName, price);
    setWebsite(webSite);
}

//accessor methods
public void setWebsite(String webSite)
{
    this.webSite = webSite;
}
public String getWebsite ()
{
    return webSite;
}


public double discount ()
{
    return (super.getPrice()) * .10; // EBook discount of 10%
}

public String toString ()
{
    return super.toString() + "Website:" + "\t\t\t" + webSite + "\n" +
                    "EBook Discount:" + "\t\t" + usCurrency.format(discount()) + "\n";
}

} //end EBook class



public class Bookstore
{
private static Book inventoryBook[] = new Book[5];
private static NumberFormat usCurrency = NumberFormat.getCurrencyInstance(Locale.US);
static int bookIndex = 0;

public static JTextArea prepareDisplay (Book myBook, JTextArea myTextArea)
{
    myTextArea.setText("");

    myTextArea.append(myBook.toString());

    return myTextArea;
}

public static Book [] sortArray(Book[] books)
{
    // Step1
    String[] titles = new String[books.length];

    // Step2
    Book[] sortedBooks = new Book [books.length];

    // Step3
    for (int i = 0; i < books.length; i++)
    {
        titles[i] = books[i].getTitle();
    }

    // Step4
    Arrays.sort(titles, String.CASE_INSENSITIVE_ORDER);

    // Step5
    for (int i = 0; i < books.length; i++)
    {
        for (int j = 0; j < titles.length; j++)
        {
            if (books[i].getTitle().equalsIgnoreCase(titles[j]))
            {
                sortedBooks[j] = books[i];
                break;
            }
        }
    }

    return sortedBooks;
}

public static double calculateInventoryTotal(Book[] books)
{
    double total = 0;

    for (int i = 0; i < books.length; i++)
    {
        total += books[i].getPrice();
    }

    return total;
}



public static void main ( String args [])
{




    //initial array of Bookstore before anything is added
    inventoryBook [0] = new EBook ("0075260012", "David goes to School", "David Shannon", 2010, "Shannon Rock", 11.98, "http://www.tinyurl.qqwert67o9");
    inventoryBook [1] = new Book ("7423540089", "No David!", "David Shannon", 2009, "Shannon Rock", 12.99);
    inventoryBook [2] = new Book ("0743200616", "Simple Abundance", "Sarah Breathnach", 2009, "Scribner", 14.99);
    inventoryBook [3] = new EBook ("78137521819", "The very hungry caterpillar", "Eric Carle", 2005, "Philomel Books", 13.99, "http://www.tinyurl.fguopt8u90");
    inventoryBook [4] = new Book ("9781416987116", "We are going on a bear hunt", "Michael Rosen", 2009, "McElderry", 15.99);

    final Book [] newBookInventory = new Book [inventoryBook.length + 1];


    for (int i = 0; i < inventoryBook.length; i++)
    {
        newBookInventory[i] = inventoryBook[i];
    }

    inventoryBook = newBookInventory;


    //inventoryBook = sortArray(inventoryBook); 

    final double inventoryTotal = calculateInventoryTotal(newBookInventory);

    final JTextArea textArea = new JTextArea(30, 30);
    textArea.setText("");
    textArea.setEditable(false);

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(1,3));

    JButton firstButton = new JButton("First");
    buttonPanel.add(firstButton);
    firstButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            bookIndex = 0;
            prepareDisplay(inventoryBook[bookIndex], textArea);
            textArea.append("\n Total Inventory Value: " + "\t\t" + usCurrency.format(inventoryTotal));
        }
    });

    JButton previousButton = new JButton("Previous");
    buttonPanel.add(previousButton);
    previousButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            if(bookIndex == 0) 
            {
                bookIndex = inventoryBook.length - 1;
            } 
            else 
            {
                bookIndex = bookIndex - 1;
            }
            prepareDisplay(inventoryBook[bookIndex], textArea);
            textArea.append("\n Total Inventory Value: " + "\t\t" + usCurrency.format(inventoryTotal));
        }
    });

    JButton nextButton = new JButton("Next");
    buttonPanel.add(nextButton);
    nextButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            if(bookIndex == inventoryBook.length - 1) 
            {
                bookIndex = 0;
            } 
            else 
            {
                bookIndex = bookIndex + 1;
            }
            prepareDisplay(inventoryBook[bookIndex], textArea);
            textArea.append("\n Total Inventory Value: " + "\t\t" + usCurrency.format(inventoryTotal));
        }
    });

    JButton lastButton = new JButton("Last");
    buttonPanel.add(lastButton);
    lastButton.addActionListener(new ActionListener()
    {   
        public void actionPerformed(ActionEvent e)
        {
            bookIndex = (inventoryBook.length - 1);
            prepareDisplay(inventoryBook[bookIndex], textArea);
            textArea.append("\n Total Inventory Value: " + "\t\t" + usCurrency.format(inventoryTotal));
        }
    });


    JButton searchButton = new JButton("Search");
    buttonPanel.add(searchButton);
    searchButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            boolean matchFound = false;
            String searchCriteria = JOptionPane.showInputDialog("Enter Book Title");

            for (int i = 0; i < inventoryBook.length; i++)
            {
                if (inventoryBook[i].getTitle().equalsIgnoreCase(searchCriteria))
                {
                    matchFound = true;
                    bookIndex = i;
                    break;
                }
            }

            if (matchFound)
            {
                prepareDisplay(inventoryBook[bookIndex], textArea);
            }
            else
            {
                JOptionPane.showMessageDialog( null, "Book Title " + searchCriteria + " does not exist.");
            }
        }
    });

    JButton modifyButton = new JButton("Modify");
    buttonPanel.add(modifyButton);
    modifyButton.addActionListener(new ActionListener ()
    {
        public void actionPerformed(ActionEvent e)
        {
            String title = JOptionPane.showInputDialog(null, "Enter Book Title", inventoryBook[bookIndex].getTitle());
            if (title != null)
            {
                String isbn = JOptionPane.showInputDialog(null, "Enter ISBN", inventoryBook[bookIndex].getISBN());
                if (isbn != null)
                {
                    String authorName = JOptionPane.showInputDialog(null, "Enter Author's Name", inventoryBook[bookIndex].getAuthorName());
                    if (authorName != null)
                    {
                        String yearPublished = JOptionPane.showInputDialog(null, "Enter Year Published", inventoryBook[bookIndex].getYearPublished());
                        if (yearPublished != null)
                        {
                            String publisherName = JOptionPane.showInputDialog(null, "Enter Publisher Name", inventoryBook[bookIndex].getPublisherName());
                            if (publisherName != null)
                            {
                                String price = JOptionPane.showInputDialog(null, "Enter Price", inventoryBook[bookIndex].getPrice());
                                if (price != null)
                                {
                                    inventoryBook[bookIndex].setTitle(title);
                                    inventoryBook[bookIndex].setISBN(isbn);
                                    inventoryBook[bookIndex].setAuthorName(authorName);
                                    inventoryBook[bookIndex].setYearPublished(Integer.parseInt(yearPublished));
                                    inventoryBook[bookIndex].setPublisherName(publisherName);
                                    inventoryBook[bookIndex].setPrice(Double.parseDouble(price));

                                    prepareDisplay(inventoryBook[bookIndex], textArea);
                                }
                            }
                        }
                    }
                }
            }
        }
    });


    JButton addButton = new JButton("Add");
    buttonPanel.add(addButton);
    addButton.addActionListener(new ActionListener ()
    {
        public void actionPerformed(ActionEvent e)
        {
            String title = JOptionPane.showInputDialog(null, "Enter Title");
            if (title != null)
            {
                String isbn = JOptionPane.showInputDialog(null, "Enter ISBN");
                if (isbn != null)
                {
                    String authorName = JOptionPane.showInputDialog(null, "Enter Author's Name");
                    if (authorName != null)
                    {
                        String yearPublished = JOptionPane.showInputDialog(null, "Enter Year Published");
                        if (yearPublished != null)
                        {
                            String publisherName = JOptionPane.showInputDialog(null, "Enter Publisher Name");
                            if (publisherName != null)
                            {
                                String price = JOptionPane.showInputDialog(null, "Enter Price");
                                if (price != null)
                                {


                                    Book newBook = new Book (title, isbn, authorName, (Integer.parseInt(yearPublished)), publisherName,(Double.parseDouble(price)));
                                    inventoryBook[newBookInventory.length - 1] = newBook;
                                    prepareDisplay(inventoryBook[bookIndex], textArea);
                                }
                            }
                        }
                    }
                }
            }
        }
    });




    JLabel logoLabel = new JLabel (new ImageIcon("GoblinBooks.jpg"));
    JPanel logoPanel = new JPanel();
    logoPanel.add(logoLabel);

    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));
    centerPanel.add(prepareDisplay(inventoryBook[bookIndex], textArea));




    //for (int i = 0; i < inventoryBook.length; i++ )
    //{
    //  textArea.append(inventoryBook[i] + "\n");
    //}



    textArea.append("Total Inventory Value: " + "\t\t" + usCurrency.format(inventoryTotal));

    JFrame frame = new JFrame();
    frame.setLayout(new BorderLayout());
    frame.add(logoPanel, BorderLayout.NORTH);
    frame.add(buttonPanel, BorderLayout.SOUTH);
    frame.add(centerPanel, BorderLayout.CENTER);
    frame.getContentPane().add(new JScrollPane(textArea));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}
} // end class Bookstore

疯了,再次感谢你,我理解的是null本身,我不确定我是否要取消这些书的价值,我会在这里返回什么。它应该看起来像这样,但我不确定如何在任何添加之前计算原始库存。非常感谢任何和所有帮助!

public static double calculateInventoryTotal(Book[] books)
{


    double total = 0;

    for (int i = 0; i < books.length; i++)
    {
        total += books[i].getPrice();
        if(books[i]!= null) return ???;
    }

    return total;
}

1 个答案:

答案 0 :(得分:1)

问题是arraycalculateInventoryTotal null本书final Book [] newBookInventory = new Book [inventoryBook.length + 1]; 中的元素之一<{1}}

这是由此引起的

inventoryBook

然后使用null中的内容填充此数组,但最后一个元素为null

在尝试访问数组中的元素之前,在calculateInventoryTotal方法中添加null项检查

基本上,数组是一系列“桶”,“可能”包含对象的引用。在尝试访问任何属性之前,您需要检查您要检查的元素是否为for (int i = 0; i < books.length; i++) { if(books[i]!= null) { total += books[i].getPrice(); } } ,例如

{{1}}