java - 使用 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: ");
};
我真的很感激帮助!
解决方案
在您的Store
班级中,货物数组未初始化。如果您将其更改为
private ArrayList<T> goods = new ArrayList<>();
推荐阅读
- php - 如何使用 Linkedin Api 获取所有 Linkedin 个人资料帖子
- android - > 无法解析配置 ':app:_internal_aapt2_binary' 的所有文件
- ios - 如何使用 swift 将数据从本地 JSON 加载到表格视图中的标签
- sql - SQL Server:加入/合并表
- javascript - 在另一个类中访问异步函数,对对象属性给出空白响应如何解决这个问题?
- kotlin - 确定两个列表是否包含相同的不同项目
- python - 返回类型取决于输入列表项类型的类型提示函数
- html-framework-7 - Framework7导航不起作用
- azure-web-app-service - 将 ASP.NET Core 5 应用程序从 Windows 移动到 Linux 后出现 InvalidCastException
- textbox - 防止从文本框和您的应用程序 vb.net 失去焦点