java预期输出的值未显示
我实例化了SpaceStation类并调用了addAstronaut
方法,但在运行它时,名称、重量、高度和宇航员没有显示在我的输出中
空间站。爪哇:
public class SpaceStation {
//private members
private String name;
private double stationWeight;
private double altitude;
private Astronaut[] 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 = new Astronaut[3];
stationWeight = stationWeight + weight;
totalAstronauts++;
}
public double setAltitude(double altitude) { return this.altitude = altitude; }
public String toString() {
return "SpaceStation: " + name + "\n" +
"Weight(kg): " + stationWeight + "\n" +
"Altitude(km): " + (altitude) + "\n" +
"Astronauts: " + (totalAstronauts);
}
public static void main(String[] args) {
SpaceStation aa = new SpaceStation("ISS", 419700.0);
System.out.println(aa);
aa.addAstronaut("Eli", 167.64, 81.65);
aa.addAstronaut("John", 185.43, 100.30);
aa.addAstronaut("Joey", 175.38, 90.38);
aa.setAltitude(400.0);
}
}
# 1 楼答案
您的代码包含四个错误:
1-您没有在构造函数中设置实例变量
name
的内容。这会在打印输出时导致行SpaceStation: null
。您需要在构造函数中设置名称。将构造函数更改为如下所示:2-在添加宇航员和设置高度之前,您正在打印
ss
的内容。当时没有增加宇航员,所以重量、宇航员人数和高度都是0是正常的。如果你在完成这些操作后打印出空间站的内容,它就会工作:3-正如@sagi标记的那样,在构造函数中,您正在声明和初始化另一个变量,而不是在类中,但名称相同。从技术上讲,double和integer已经用0.0初始化了,所以你不会真正注意到它,但是构造函数中的变量
altitude
和totalAstronauts
实际上是无用的。建议如下更新构造函数:4-当@sagi标记时,每次添加宇航员时,都会初始化
Astronaut
数组。你需要在构造器中初始化它一次,并在每次添加一个时在阵列中设置宇航员有了所有这些注释,
SpaceStation
类应该是这样的:# 2 楼答案
(1)空间站的构造函数没有将传入的名称和权重值设置为空间站对象的参数。将
this.name = name
和this.stationWeight = weight
添加到构造函数中。this
关键字告诉Java,您所引用的变量是调用构造函数的对象的参数构造函数还创建名为
altitude
和totalAstronauts
的新变量,这些变量仅存在于构造函数内部。要更改调用构造函数的对象的参数值,请向构造函数添加this.altitude = altitude
和this.totalAstronauts = totalAstronauts
(2)主方法在对其执行操作之前打印
ss
。将其放在主代码中的其他代码之后:(3)每次调用AddSpauton()时,都会覆盖宇航员数组。通过创建一个新的宇航员实例并将其添加到AddSpauton()中的宇航员数组中,可以解决这个问题。应该在构造函数中添加一行,以将数组初始化为大小为3或更大的空数组,这样就有空间在AddSpauton()中添加宇航员对象
# 3 楼答案
主要有两个错误导致
name
显示为空1:您没有在构造函数中设置
name
,这导致name
的默认值为null
所以当你说
this.name = name
它告诉我我有这个,请看并设置它的值同样在
main
函数中,您试图在设置值之前打印它。 你应该先给出它的值,然后再打印出来此外,我看到你制作了一个
Astronaut[] Astronauts
阵列,但从未在其中添加任何宇航员。那么它的全部意义是什么呢? 添加宇航员时,它只存储astronauts
的总数,而不存储实际的Astronauts Object
主要内容:
宇航员班:
输出: