Reputation: 129
How can I insert objects into an array? Here I have a class called HotelRoom which contains getter, setter, and the constructor method.
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;
}
And here I have the main method containing the array initializer and the objects. I've also inserted the objects into the array however, when compiling, the problem arises in the print command and it states: "cannot find symbol - variable HotelRoom". What am I doing wrong?
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);
}
}
Upvotes: 0
Views: 99
Reputation: 195
At first implement toString()
in the HotelRoom
:
public String toString() {
return roomNumber + " " + roomGuest;
}
And then print the right array:
System.out.println(Arrays.toString(rooms));
Upvotes: 0
Reputation: 3236
HotelRoom is the name of the class. The objects are now in the rooms array. If you are wanting to print out the array, try printing rooms, or a particular place in the array, e.g
System.out.println(rooms[0].getName());
Upvotes: 0
Reputation: 11939
This is because HotelRoom
is a class, not an Object
. If you have intentions of printing out all of the rooms, perhaps you could try something like:
for(final HotelRoom room : rooms)
System.out.printf("%s in room %d\n", room.getName(), room.getRoom());
Or you could override the toString()
method in HotelRoom
:
public String toString(){
return String.format("%s in room %d", roomGuest, roomNumber);
}
With the overridden toString()
method, you can now modify your loop to:
for(final HotelRoom room : rooms)
System.out.println(room);
Or, if you want:
System.out.println(Arrays.toString(rooms));
Upvotes: 4