我正在尝试创建一个删除项目的删除按钮。这里的目标是当用户选择删除键时,它删除当前条目并将所有剩余项目复制到新的临时数组。请注意,我仍然在学习,只是寻求正确方向的帮助,虽然也欢迎解决方案,因为我也可以向他们学习。我得到的错误是很长的,根据我以前的经验,我想与使用空检查有关,我只是不确定它应该在哪里提供。
这是错误
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Bookstore$8.actionPerformed(Bookstore.java:435)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
这是按钮的代码
JButton deleteButton = new JButton("Delete");
buttonPanel.add(deleteButton);
deleteButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent p)
{
//#1
Book[] tempBook = new Book[inventoryBook.length - 1];
//#2
Book itemDelete = inventoryBook[bookIndex];
int j = 0;
for (int i = 0; i < inventoryBook.length; i++)
{
if (inventoryBook[i].getISBN() != itemDelete.getISBN())
{
tempBook[j] = inventoryBook[i];
j++;
}
}
sortArray(tempBook);
inventoryBook = tempBook;
prepareDisplay(inventoryBook[bookIndex], textArea);
}
});
请注意,只有在用户选择“删除”按钮时才会出现此错误。没有编译错误。
下面我已经包含了编译或查看其他所有内容的完整代码。
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;
private static Book [] newBookInventory = new Book [inventoryBook.length + 1];
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++)
{
if(books[i]!= null)
{
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);
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 isbn = JOptionPane.showInputDialog(null, "Enter ISBN");
if (isbn != null)
{
String title = JOptionPane.showInputDialog(null, "Enter Title");
if (title != 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 (isbn, title, authorName, (Integer.parseInt(yearPublished)), publisherName,(Double.parseDouble(price)));
inventoryBook[newBookInventory.length - 1] = newBook;
prepareDisplay(inventoryBook[bookIndex], textArea);
}
}
}
}
}
}
}
});
JButton deleteButton = new JButton("Delete");
buttonPanel.add(deleteButton);
deleteButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent p)
{
//#1
Book[] tempBook = new Book[inventoryBook.length - 1];
//#2
Book itemDelete = inventoryBook[bookIndex];
int j = 0;
for (int i = 0; i < inventoryBook.length; i++)
{
if(inventoryBook[i].getISBN() != itemDelete.getISBN())
{
tempBook[j] = inventoryBook[i];
j++;
}
}
sortArray(tempBook);
inventoryBook = tempBook;
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
答案 0 :(得分:0)
这可能与您previous question的问题相同,数组中的一个或多个元素为null
您将数组声明为...
private static Book inventoryBook[] = new Book[5];
private static Book [] newBookInventory = new Book [inventoryBook.length + 1];
然后将inventoryBook
的内容复制到newBookInventory
,一次只复制一个元素......
for (int i = 0; i < inventoryBook.length; i++)
{
newBookInventory[i] = inventoryBook[i];
}
inventoryBook = newBookInventory;
这意味着inventoryBook
和newBookInventory
在数组末尾都有一个null
元素。
然后迭代inventoryBook
,访问每个元素的getISBN
方法,而不先检查该元素是否为null
int j = 0;
for (int i = 0; i < inventoryBook.length; i++)
{
if (inventoryBook[i] != null) {
if (inventoryBook[i].getISBN() != itemDelete.getISBN())
{
tempBook[j] = inventoryBook[i];
j++;
}
}
}
甚至可能值得检查itemDelete
以确保它不是null
,但我没有阅读那么多代码