原谅我,我是Java新手!而且对于一个大学项目,我遇到了一些概念的麻烦,我试图谷歌周围无济于事!如何在MarsRoom类中实例化一定数量的加热器类加热器,然后在MasterControlPanel的主体中访问它们。但是取决于构造函数中设置的numheater的数量??我试过这个,但它没有认识到对象room1.roomheaters [0]。然而,如果我只是实例化像加热器roomheaters = new Heaters();这样的一个对象,它确实会认出它。 非常感谢
public class MasterControlPanel{
public static void main(String[] args){
MarsRoom room1 = new MarsRoom(40, 40, 20, 20, 8, 2, 4);
MarsRoom room2 = new MarsRoom(40, 40, 20, 20, 8, 2, 4);
MarsRoom room3 = new MarsRoom(40, 40, 20, 20, 8, 2, 4);
MarsRoom room4 = new MarsRoom(40, 40, 20, 20, 8, 2, 4);
room1.createheaters();
System.out.println("Turned " + (room1.roomheaters[0].getHeater() ? " ON" : " OFF"));
}
}
public class MarsRoom extends Rooms implements RoomInterface{
int roomareasq;
int heatloss;
float insideTemp;
float outsideTemp;
float uvalue;
int numheaters;
int numlights;
Heaters roomheaters[] = new Heaters[numheaters];
public MarsRoom(){
}
public MarsRoom(int windowsH, int windowsW, int wallsH, int wallsW, int windowC, int heaters, int lights){
windowsHeight = windowsH;
windowsWidth = windowsW;
wallsHeight = wallsH;
wallsWidth = wallsW;
windowCeiling = windowC;
numheaters = heaters;
numlights = lights;
}
public void createheaters(){
for (int i=0; i < numheaters; i++)
{
roomheaters[i] = new Heaters();
}
}
public void calculateheatloss(){
}
}
答案 0 :(得分:2)
数组roomheaters
永远不会被声明,所以不可能填充它,更不用说从另一个类作为MarsRoom
的属性访问它了:
roomheaters[i] = new Heaters();
// variables must be declared to be assigned
查看declaring member variablesOracle
<强>更新强>
要将变量作为对象属性(如room1.roomheaters[0]
)进行访问,它必须是成员变量。您只创建了一个 local 变量,该变量在函数返回后立即消失。上面的链接应该有所帮助。
答案 1 :(得分:1)
您必须将roomheaters的实例化移出函数和类变量,并创建一个方法来访问加热器。在MarsRoom类中添加:
public Heaters[] getHeaters(){
return roomheaters;
}
您可以致电room1.getHeaters()