java - 当我尝试将类的内容添加到数组时程序崩溃
问题描述
我正在尝试向数组中添加一个类,并且在我的类中的线程“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;
}
解决方案
您需要初始化Astronauts
数组。尝试类似:
Astronauts = new Object[10];
在 for 的构造函数中SpaceStation
,将数组的大小作为该构造函数的输入,或者使用ArrayList
for 可变大小列表。
推荐阅读
- parsing - 有没有办法在前端编写没有抽象语法树的编译器?
- swift - 小时和分钟的 UIDatePicker CountDownMode 语言环境
- excel - 填充动态列
- r - R为函数定义列
- asp.net - 无法从 IActionModelConvention 实施的应用方法中的授权属性访问角色
- php - 将一对多关系更改为多对多关系?
- ios - 将 JSON 响应分配给模型 SwiftUI
- android - 以编程方式禁用浮动操作按钮
- xslt - XSL fo:block long word not wrap in table cell
- javascript - 在任何地方使用 CORS 进行请求时缺少所需的请求标头