首页 > 解决方案 > 当我尝试将类的内容添加到数组时程序崩溃

问题描述

我正在尝试向数组中添加一个类,并且在我的类中的线程“main”java.lang.NullPointerException 中出现异常addAstronaut

package gov.nasa.spacevehicles;

import gov.nasa.personnel.Astronaut;

public class SpaceStation {

//private members
   private String name;
   private double stationWeight;
   private double altitude;

private Object[] Astronauts;
private int totalAstronauts;

//overloaded constructor
public SpaceStation(String name, double weight) {
   int altitude = 0;
   int totalAstronauts = 0; 
}

//method
public void addAstronaut(String name, double height, double weight) {
     Astronauts[0] = new Astronaut(); // Exception in thread
     Astronauts[1] = new Astronaut();
     Astronauts[2] = new Astronaut();

    
     stationWeight = stationWeight + weight;  
 }

标签: java

解决方案


您需要初始化Astronauts数组。尝试类似:

Astronauts = new Object[10];

在 for 的构造函数中SpaceStation,将数组的大小作为该构造函数的输入,或者使用ArrayListfor 可变大小列表。


推荐阅读