0

I've stack with a selectItem() method. If I run it I get this error "java.lang.NullPointerException". Definetly a problem with arrayList , but I cant find out. Any help, please. Or an ArrayList better to create in a Dispenser class?
If your need any more information I can give it. Thanks.

    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" );
        }

     }
Ben
  • 1

1 Answers1

0

Inside your public void selectItem(String itemName) function, I think (guess here) you are referring the variable inside the loop using disp reference rather than product.

         for(Dispenser product : items){
            if(product.getName() == itemName){//<--here
               System.out.println("Get Your " + itemName);
         }
Aragorn
  • 5,021
  • 5
  • 26
  • 37
  • Looks like that to me too. The variable disp does not seem to be initialised at the point it is being used here. The product variable seems like the logical thing to use. – ewanc Nov 30 '15 at 21:31