- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在已实现的 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
Mad,再次感谢您,null 本身我理解,我不确定是否要将 books[i] 值设为 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;
}
最佳答案
问题是calculateInventoryTotal
中的书籍array
中的元素之一为null
这是由此造成的
final Book [] newBookInventory = new Book [inventoryBook.length + 1];
然后用 inventoryBook
中的内容填充此数组,但最后一个元素为 null
在尝试访问数组中的元素之前,在 calculateInventoryTotal
方法中添加 null
检查
基本上,数组是一系列“桶”,其中“可能”包含对对象的引用。例如,在尝试访问它的任何属性之前,您需要检查要检查的元素是否不为 null
for (int i = 0; i < books.length; i++)
{
if(books[i]!= null) {
total += books[i].getPrice();
}
}
关于Java 添加按钮 GUI 增长数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21663966/
增长,则让
当我输入内容时,如何移动 p 段落下方的所有元素,即 contenteditable。 这是我的代码: body, html { margin: 0; padding: 0; backgr
我要解决的问题: 我有一个包含 div 的外部 div。 content 内部和外部 div 之间的边距应始终相同。 当内部 div 增长/收缩时,外部 div
这document Ulrich Drepper 称为“图书馆设计、实现和维护的良好实践”(第 5 页底部): [...] the type definition should always crea
有什么方法可以获取 QPainterPath 并将其展开,就像 Photoshop 中的“选择”>“增长...”(或“展开...”)命令一样? 我想获取从 QGraphicsItem::shape 返
假设,为了问题的目的,我们有一个内存池,最初分配了 n 个 block 。但是,当达到容量时,池想要增长并变成原来大小的两倍 (2n)。 现在可以使用 C 中的 realloc 完成此调整大小操作,但
假设,为了问题的目的,我们有一个内存池,最初分配了 n 个 block 。但是,当达到容量时,池想要增长并变成原来大小的两倍 (2n)。 现在可以使用 C 中的 realloc 完成此调整大小操作,但
我正在研究 boost 库的共享内存部分,为更大的项目做准备。我需要一个共享内存段,在初始化时我不一定知道它的大小,所以我的计划是增加这个段。 我的初始实现有一个存储在共享内存中的 boost::in
这个问题在这里已经有了答案: How to disable equal height columns in Flexbox? (4 个答案) What are the differences bet
我有一个包含子表的表。我不希望子表影响表格的宽度——在溢出的情况下,我希望两者独立滚动。此外,由于子表是基于切换显示的,所以我不希望主表行根据子表是否可见而跳转 Here's代码笔。 我想我可以用 t
我有一个带栏的页面设计,它可以有一个、两个或三个栏。这些列的大小应相同。 为此我使用了 flexbox,它很好,允许我添加/删除我的列并让浏览器处理列宽的大小调整。 现在,当列中的文本大于列的宽度时,
要求: 我需要根据数据增长一个任意大的数组。 我可以猜测大小(大约 100-200),但不能保证数组每次都能适合 一旦它增长到最终大小,我需要对其执行数值计算,因此我更愿意最终得到一个二维 numpy
我有一个 3x256 规则的规则集。每个规则映射到一个 3x3 的值网格,这些值本身就是规则。 规则示例: 0 -> [[0,0,0],[0,1,0],[0,0,0]] 1 -> [[1,1,1],
我有 3 个 div,如果我给前两个 div flex: 0.5,如果我给了 flex-wrap: wrap,最后一个 div 应该移动到下一行>。如果我错了,请指正。 以下是我的 html/css:
在文档和 Bootstrap v4 问题中 (here) ,我看不到任何支持 flex-grow 的计划,例如语法如下: I use all the space lef
要求: 我需要从数据中增加一个任意大的数组。 我可以猜测大小(大约 100-200),但不能保证每次都适合数组 一旦它增长到最终大小,我需要对其执行数值计算,因此我希望最终得到一个二维 numpy 数
我知道(并在互联网上阅读-包括此资源)。增加内存的逻辑是:如果len数组小于1024-golang将array乘以2,否则将len乘以1.25(并且我们在源代码中看到了这个问题https://gith
当输入长文本时,WPF TextBox 控件会增长。 这个问题已经在 Stackoverflow 中提出了 我也引用了一些答案,但我仍然没有找到有效的正确答案。 Here提到了同样的问题,但没有针对此
我在使用 Vaadin HorizonalLayout 时遇到问题 - 我希望左侧组件填充大部分水平空间,如 Fiddle 所示 但是,当我运行 Vaadin 应用程序时,这两个组件会平分屏幕。
关于这个fiddle , 当我点击 a href在这种情况下这是一个图像,我希望图像从 div 开始增长/过渡以通过过渡/缩放填充整个页面它被放置在其中。如果这不可能,我想用 div 的背景颜色填充页
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 6 年前。 Improve this q
我是一名优秀的程序员,十分优秀!