gpt4 book ai didi

java - 包含对象的二维数组

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

这是一项涉及创建酒店宾客服务的类(class)作业。我创建了下面的二维数组,其中包含 8 个“楼层”、20 个“房间”,并用 Room 对象填充它们。我目前正在尝试使用嵌套的 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 对象分配唯一的房间号?

最佳答案

你可以做

for (int floor=0; floor<hotelBuild.length; floor++){
for (int room=0; room<hotelBuild[floor].length; room++){
Room r = new Room();
r.setRoomNumber(
cleverCalculationWithFloorAndRoomNr(floor, room));
hotelBuild[floor][room]= r;

关于java - 包含对象的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18586674/

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