原谅我,我是Java新手!并且是用于一个大学项目,我在一些概念上遇到了麻烦,我试图在Google周围搜索都无济于事!如何在MarsRoom类内部实例化一定数量的加热器类的加热器,然后在MasterControlPanel的主目录中对其进行访问。但是取决于构造函数中设置的数字加热器数量。我已经尝试过了,但是它无法识别对象room1.roomheaters [0]。但是,如果我只实例化一个对象(例如Heaters 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(){

}

}

最佳答案

数组roomheaters从未声明过,因此无法填充它,更不用说从另一个类将其作为MarsRoom的属性来访问了:

roomheaters[i] = new Heaters();
// variables must be declared to be assigned


看看declaring member variables



更新

要将变量作为对象属性(如room1.roomheaters[0])访问,它必须是成员变量。您只创建了一个局部变量,该局部变量在函数返回后立即消失。上面的链接应该有所帮助。

10-06 16:14