Tuesday, 3 September 2013

2d Array containing objects

2d Array containing objects

This is an assignment for class that involves creating a hotel guest
service. I created the 2d array below with 8 "floors", 20 "rooms", and
populated them with Room objects. I am currently trying to use nested
for-loops to go through each Room object and assign it a room number. For
example, floor 1 would contain rooms 101-120.
The class below is a test class that I am using.
public class Test {
public Test() {
}
public static void main(String[] args) {
/**
*Creates a two dimensional array with 8 rows and 20 columns
*/
Room [][] hotelBuild = new Room[8][20];
/**
*populates the 2d array with Room objects
*/
for (int floor=0; floor<hotelBuild.length; floor++){
for (int room=0; room<hotelBuild[floor].length; room++){
hotelBuild[floor][room]=new Room();
/**
* used to print out contents of 2d array
*/
//System.out.print(hotelBuild[floor][room]=new Room());
}
}
}
}
Below is class Room that contains the variables, setters, getters, as well
as the toString() override method.
public class Room {
//Instance variables
/**
*the rooms number
*/
private int roomNumber;
/** is the room occupied or not
*
*/
private boolean isOccupied;
/** name of guest
*
*/
private String guest;
/** cost per day
*
*/
private double costPerDay;
/** number of days guest is staying
*
*/
int days;
//Constructors
public Room(){
}
/** Construct a room with values above
*
*/
public Room(int room, boolean nonVacant, String guestName, double cost,
int day) {
roomNumber = room;
isOccupied = nonVacant;
guest = guestName;
costPerDay = cost;
days = day;
}
// getters
/** gets roomNumber
*
*/
public int getRoomNumber(){
return roomNumber;
}
/** gets isOccupied
*
*/
public boolean getIsOccupied(){
return isOccupied;
}
/** gets guest
*
*/
public String getGuest(){
return guest;
}
/** gets costPerDay
*
*/
public double getCostPerDay(){
return costPerDay;
}
/** gets days
*
*/
public int getDays(){
return days;
}
// setters
/** sets isOccupied
*
*/
public void setIsOccupied(boolean full){
this.isOccupied = full;
}
/** sets days
*
*/
public void setDays(int numDays){
this.days = numDays;
}
/** sets guest name
*
*/
public void setGuest(String name){
this.guest = name;
}
/** formats output depending if room is occupied or not
*
*/
public String toString(){
if(isOccupied == true){
return "Room number: " + roomNumber + "\n"+ "Guest name: "
+ guest + "\n"+ "Cost : " + costPerDay
+ "\n"+ "Days: " + days + "\n";
}
else{
return "Room number " + roomNumber
+ " costs " + costPerDay + "\n";
}
}
}
How do I assign each Room object in the array a unique room number?

No comments:

Post a Comment