程序在我尝试将一个类的内容添加到一个数组时崩溃。

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年9月28日 09:49:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/64094980.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定