我使用selectItem()方法进行堆叠。如果我运行它我得到这个错误“java.lang.NullPointerException”。
绝对是arrayList的一个问题,但我无法找到答案。
请帮忙。
或者更好地在Dispenser类中创建ArrayList?
如果您需要更多信息我可以给它。感谢。
public class Dispenser
{
private String name; // Item name.
private int price; //Item cost.
private int stock; // Total quantity in stock.
/**
* Create a new dispenser with the given details.
* At the start it has 5 items in stock.
*/
public Dispenser(String itemName, int itemPrice)
{
name = itemName;
price = itemPrice;
stock = 5;
}
/**
* Return an item name.
* @return Item name.
*/
public String getName()
{
return name;
}
import java.util.*;
/**
* Main class for a vending mashine.
*/
public class VendingMachine
{
private Dispenser disp;
private CoinBox box;
private int credit;
private ArrayList<Dispenser> items = new ArrayList<Dispenser>();
/**
* Constructor.
*/
public VendingMachine()
{
credit = 0;
items.add(new Dispenser("Snickers", 55));
items.add(new Dispenser("Mars", 50));
items.add(new Dispenser("Bounty", 75));
}
public void selectItem(String itemName)
{
for(Dispenser product : items){
if(disp.getName() == itemName){
System.out.println("Get Your " + itemName);
}
}
if((disp.getName() != itemName)){
System.out.println( itemName + " is Out of stock" );
}
}
答案 0 :(得分:0)
在public void selectItem(String itemName)
函数中,我想(猜猜在这里)你使用disp
引用而不是product
引用循环内的变量。
for(Dispenser product : items){
if(product.getName() == itemName){//<--here
System.out.println("Get Your " + itemName);
}