这是涉及创建酒店宾客服务的课程作业。Room
我用 8 个“楼层”、20 个“房间”创建了下面的二维数组,并用对象填充它们。我目前正在尝试使用嵌套的 for 循环来遍历每个 Room 对象并为其分配一个房间号。例如,第 1 层将包含房间 101-120。
下面的类是我正在使用的测试类。
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());
}
}
}
}
下面是Room
包含变量、setter、getter 以及toString()
覆盖方法的类。
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";
}
}
}
如何Room
为数组中的每个对象分配一个唯一的房间号?