gpt4 book ai didi

java - 如何将对象插入数组?

转载 作者:行者123 更新时间:2023-12-01 18:36:55 25 4
gpt4 key购买 nike

如何将对象插入数组?这里我有一个名为 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 方法。我还将对象插入到数组中,但是在编译时,打印命令中出现了问题,它指出:“找不到符号 - 变量 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);
}

}

最佳答案

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

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

或者您可以重写 HotelRoom 中的 toString() 方法:

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));

关于java - 如何将对象插入数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21583711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com