【问题标题】:java.lang.NullPointerException when using switch case [duplicate]java.lang.NullPointerException 使用 switch case [重复]
【发布时间】:2021-06-04 18:24:19
【问题描述】:

我在编译代码时收到 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: ");
    };

我真的很感谢您的帮助!

【问题讨论】:

    标签: java nullpointerexception switch-statement


    【解决方案1】:

    在您的Store 类中,商品数组未初始化。如果您将其更改为,它将起作用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多