英文:
Program crashes when I try to add contents of a class to on array
问题
我正在尝试将一个类添加到数组中,但是在我的addAstronaut
类中出现了**“主”线程中的异常“java.lang.NullPointerException”**。
package gov.nasa.spacevehicles;
import gov.nasa.personnel.Astronaut;
public class SpaceStation {
// 私有成员
private String name;
private double stationWeight;
private double altitude;
private Object[] Astronauts;
private int totalAstronauts;
// 载荷构造函数
public SpaceStation(String name, double weight) {
int altitude = 0;
int totalAstronauts = 0;
}
// 方法
public void addAstronaut(String name, double height, double weight) {
Astronauts[0] = new Astronaut(); // 异常线程
Astronauts[1] = new Astronaut();
Astronauts[2] = new Astronaut();
stationWeight = stationWeight + weight;
}
}
英文:
I am trying to add a class to an array and I get Exception in thread "main" java.lang.NullPointerException in my addAstronaut
class.
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;
}
答案1
得分: 0
你需要初始化Astronauts
数组。尝试类似这样的操作:
Astronauts = new Object[10];
在SpaceStation
的构造函数中,将数组的大小作为该构造函数的输入,或者使用ArrayList
来实现可变大小的列表。
英文:
You need to initialize the Astronauts
array. Try something like:
Astronauts = new Object[10];
in the constructor for SpaceStation
, take the size of the array as an input to that constructor, or use an ArrayList
for variable size lists.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论