因此,我已经在这段代码上方坐了一段时间,准备好NullPointerException线程,但仍然无法弄清楚代码中出了什么问题,因此我转向您。
public class Main {
public static void main(String[] args){
/* Making catalog, loading last state */
Collection catalog = new Collection();
try {
catalog.readFromFile();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
catalog.addShip(new Ship("ABC123", "John", "Suzuki", 50));
}
}
我的Collection类如下所示:
public class Collection {
private List<Ship> shipList;
private String fileName = "catalog.txt";
private int income;
private int space;
public Collection() {
shipList = new ArrayList<Ship>();
income = 0;
space = 500;
File f = new File("catalog.txt");
if(!f.exists()) {
try {
f.createNewFile();
writeToFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void addShip(Ship SHIP){
space -= SHIP.LENGTH;
income += SHIP.COST;
shipList.add(SHIP);
}
public Ship getShip(int INDEX){
return shipList.get(INDEX);
}
public void writeToFile() throws IOException {
FileOutputStream f = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(f);
out.writeObject(shipList);
out.close();
}
@SuppressWarnings("unchecked")
public void readFromFile() throws IOException, ClassNotFoundException {
FileInputStream f = new FileInputStream(fileName);
ObjectInputStream in = new ObjectInputStream(f);
shipList = (ArrayList<Ship>)in.readObject();
in.close();
}
public int getIncome(){
return income;
}
public int getSpace(){
return space;
}
}
我的问题是,当我在主
catalog.addship()
中调用时,出现nullptr错误。遵循控制台错误后,它说我在目录上调用addShip()
时得到了nullptrexc,然后从那里得到错误消息,当我add()
运送到集合的shipList
时出现了错误。所以我得出的结论是,因为Collection中的shipList未初始化。但是在构造函数中,我写了shipList = new ArrayList<Ship>();
,因此显然已初始化。异常堆栈跟踪如下:
Exception in thread "main" java.lang.NullPointerException
at collection.Collection.addShip(Collection.java:31)
at main.Main.main(Main.java:100)
最佳答案
在您的main方法中,您可以正确初始化ArrayList。但是,然后,
catalog.readFromFile()
呼叫。在readFromFile()方法中,您重新初始化ArrayList
shipList = (ArrayList<Ship>)in.readObject();
in.readObject()返回null。这就是为什么shipList变量为null的原因。
希望这可以帮助!