如何将对象插入数组?

时间:2014-02-05 17:04:18

标签: java arrays

如何将对象插入数组?这里我有一个名为HotelRoom的类,它包含getter,setter和构造函数方法。

public class HotelRoom {

int roomNumber;
String roomGuest;


public HotelRoom (int room, String guest) {
    roomNumber = room;
    roomGuest = guest;
}

public int getRoom() {
    return roomNumber;
}

public void setRoom() {
    roomNumber = room;
}

public String getName() {
    return roomGuest;
}

public void setName() {
    roomGuest = guest;
}

这里我有一个包含数组初始化器和对象的main方法。我还将对象插入到数组中,但是在编译时,问题出现在print命令中,并指出:“找不到符号 - 变量的HotelRoom”。我究竟做错了什么?

public class Hotel {
    public static void main (String [] args) {
    HotelRoom[] rooms = new HotelRoom [5];

    HotelRoom guest1 = new HotelRoom(67, "Harry");
    HotelRoom guest2 = new HotelRoom(98, "Bob");
    HotelRoom guest3 = new HotelRoom(34, "Steven");
    HotelRoom guest4 = new HotelRoom(99, "Larry");
    HotelRoom guest5 = new HotelRoom(103, "Patrick");

    rooms[0] = guest1;
    rooms[1] = guest2;
    rooms[2] = guest3;
    rooms[3] = guest4;
    rooms[4] = guest5;

    System.out.println (HotelRoom);
}

}

3 个答案:

答案 0 :(得分:4)

这是因为HotelRoom是一个类,而不是Object。如果您打算打印出所有房间,也许您可​​以尝试以下方式:

for(final HotelRoom room : rooms)
    System.out.printf("%s in room %d\n", room.getName(), room.getRoom());

或者您可以覆盖toString()中的HotelRoom方法:

public String toString(){
    return String.format("%s in room %d", roomGuest, roomNumber);
}

使用重写的toString()方法,您现在可以将循环修改为:

for(final HotelRoom room : rooms)
   System.out.println(room);

或者,如果你想:

System.out.println(Arrays.toString(rooms));

答案 1 :(得分:0)

HotelRoom是班级的名称。对象现在位于房间数组中。如果您想打印阵列,请尝试打印室或阵列中的特定位置,例如

System.out.println(rooms[0].getName());

答案 2 :(得分:0)

首先在toString()

中实施HotelRoom
public String toString() {
    return roomNumber + " " + roomGuest;
}

然后打印正确的数组:

System.out.println(Arrays.toString(rooms));