我从这段代码中得到一个null异常错误,我不确定是什么导致它。数组itemcatalog已填充i = 0到8.我是java新手,所以任何帮助将不胜感激。错误消息指向while语句的行。感谢
public class ItemCatalog {
private static ItemCatalog instance = new ItemCatalog();
private Item itemCatalog[] = new Item[9];
private ItemCatalog(){
};
public static synchronized ItemCatalog getInstance() {
return instance;
}
public void populateCatalog()
{
itemCatalog[0] = new Item("bb","Baked Beans",new BigDecimal("0.35"));
itemCatalog[1] = new Item("cf","Cornflakes",new BigDecimal("1.00"));
itemCatalog[2] = new Item("s0","Sugar",new BigDecimal("0.50"));
itemCatalog[3] = new Item("tb","Tea Bags",new BigDecimal("1.15"));
itemCatalog[4] = new Item("ic","Instant Coffee",new BigDecimal("2.50"));
itemCatalog[5] = new Item("b0","Bread",new BigDecimal("0.50"));
itemCatalog[6] = new Item("s0","Sausages",new BigDecimal("1.30"));
itemCatalog[7] = new Item("e0","Eggs",new BigDecimal("0.75"));
itemCatalog[8] = new Item("m0","Milk",new BigDecimal("0.65"));
}
public BigDecimal getPrice(String itemCode)
{
int i = 0;
while (!itemCode.equals(itemCatalog[i].getItemCode()))
{
i++;
}
BigDecimal itemPrice = itemCatalog[i].getItemprice();
return itemPrice;
}
}
我解决了这个问题。我在主类中填充了目录,它给出了null异常错误。我在jframe中实例化它并且它可以工作。以下代码解决了这个问题,但这是填充目录的最佳位置吗?
private void saleButtonActionPerformed(java.awt.event.ActionEvent evt) {
String itemCode = this.itemCodeinput.getText();
int itemQuantity =Integer.parseInt(this.itemQuantityinput.getText());
ItemCatalog catalog = ItemCatalog.getInstance();
catalog.populateCatalog();
BigDecimal price = catalog.getPrice(itemCode);
itemCostoutput.setText(price.toString());
}
答案 0 :(得分:2)
如果您的itemCode与itemCatalog中的任何条目都不匹配,那么最终
while (!itemCode.equals(itemCatalog[i].getItemCode()))
{
i++;
}
将i增加到11,在这种情况下,itemCatalog [11]为空或超出范围。
如果添加,则应使用for循环遍历itemCatalog:
for (int i = 0; i < itemCatalog.length; i++) {
if (itemCode.equals(itemCatalog[i].getItemCode()) {
return (BigDecimal) itemCatalog[i].getItemprice();
}
}
return null // you can change this from null to a flag
// value for not finding the item.
答案 1 :(得分:0)
你如何结束你的循环? 似乎循环将一直持续到我10为止。那么你的意志将超过限制。
除非这是你必须使用数组的单一赋值,否则我还建议使用地图而不是数组。这样,无论您的集合有100,000个条目还是10个条目,您的查找都将是同一时间。
您还将降低NPE或ArrayOutOfBounds异常的风险
请参阅http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html
添加对象时,使用项目代码作为关键字。然后按键查找。
使用地图的成本增加了内存使用量。
答案 2 :(得分:0)
从评论中可以看出,设计并不合理。
这是一个可能的解决方案:
public BigDecimal getPrice(String itemCode) {
for (int i=0; i<itemCatalog.length; i++) { // not going outside the array
if (itemCatalog[i].getItemCode().equals(itemCode)) { // inversing the test to avoid npe if itemCode is null
return itemCatalog[i].getItemprice();
}
}
return null; // default value
}
这假设您的数组已正确填充具有itemCode的itemCatalog。