首页 > 解决方案 > 使用 switch case 时出现 java.lang.NullPointerException

问题描述

编译代码时出现 java.lang.NullPointerException,但我不知道为什么。它说:

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

我想做的是建立三个商店:铁匠铺、珠宝店和书店,然后在每个商店中随机添加物品。例如,铁匠铺只有剑和弓。我以前编程过一些非常相似的东西,没有这个问题。主要的

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 :
            }
        }

店铺类:

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++;
    }

对象类:

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

武器类:(这只是一个例子,其他两个类Ring和Scroll看起来差不多)

package fantasyGame;

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

}

剑类:(其他类看起来很相似,只是特殊技能不同)

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

我真的很感激帮助!

标签: javanullpointerexceptionswitch-statement

解决方案


在您的Store班级中,货物数组未初始化。如果您将其更改为

 private ArrayList<T> goods = new ArrayList<>();

推荐阅读