0

I get a java.lang.NullPointerException when I compile my code and I don't know why. It says:

Exception in thread "main" java.lang.NullPointerException
    at Beleg2/fantasyGame.Store.addGoods(Store.java:12)
    at Beleg2/fantasyGame.Main.main(Main.java:19)

What I am trying to do is to set up three stores: smithy, jeweler and a bookstore and then add randomly objects into each store. For example a smithy will have only swords and bows. I have programmend something very similar before without that problem. Main

package fantasyGame;

import java.util.Random;

public class Main {

    public static void main(String[] args) {
        
        
        
        Store<Weapon> smithy = new Store<>();
        Store<Ring> jeweler = new Store<>();
        Store<Scroll> bookstore = new Store<>();
        
        Random zufall = new Random();
        for(int j = 0; j < 12; j++) {
            
            switch(zufall.nextInt(6)) {
            case 0 : smithy.addGoods((Weapon)new Sword(150));
                     break;
            case 1 : smithy.addGoods((Weapon)new Bow(100));
                     break;
            case 2 : jeweler.addGoods((Ring)new Silverring(150));
                     break;
            case 3 : jeweler.addGoods((Ring)new Goldring(300));
                     break;
            case 4 : bookstore.addGoods((Scroll) new CurseOfTheQuillPen(500));
                     break;
            case 5 : bookstore.addGoods( (Scroll)new TheEyesOfHypnos(500));
                     break;
            default :
            }
        }

Store class:

package fantasyGame;

import java.util.ArrayList;

public class Store <T extends Object>{
    
    private ArrayList<T> goods;
    private int inStore = 0;
    public Store() {}
    
    public void addGoods(T x) {
        this.goods.add(x);
        this.inStore++;
    }

Object class:

package fantasyGame;

public class Object {

    private int price;
    public Object(int x) {
        this.price = x;
    }
private String specialSkill;
    public void setSpecialSkill(String s) {
        this.specialSkill = s;
    }

Weapon class: (This is just an example, the other two classes Ring and Scroll look just like it)

package fantasyGame;

public class Weapon extends Object  {
    
    public Weapon (int x) {
        super(x);
    };

}

Sword class:(The other classes look very similar just with a different specialSkill)

package fantasyGame;

public class Sword extends Weapon implements ForSaleIF {
    
    public Sword(int x) {
        super(x);
        this.setSpecialSkill("The Amount of times this sword will hit: ");
    };

I would really appriciate the help!

1 Answers1

4

In your Store class the goods array is not initialized. It will work if you change it to

 private ArrayList<T> goods = new ArrayList<>();
Harald Gliebe
  • 7,236
  • 3
  • 33
  • 38