gpt4 book ai didi

java - 如何创建一个类的不同实例?

转载 作者:行者123 更新时间:2023-11-29 10:07:29 28 4
gpt4 key购买 nike

我正在制作一个简单的程序,允许人们登记入住和退房酒店(我的 CS 类(class))。

我需要做的是检查一个房间里的人。有四个房间。我怎样才能做到当有人 checkin 时,下一个 checkin 的人将 checkin 房间 2。

我已经有了:

class Hotel {

Room room1, room2, room3, room4;

Hotel() {
room1 = new Room();
room2 = new Room();
room3 = new Room();
room4 = new Room();
}

static checkIn() {
Scanner sc = new Scanner(System.in);
System.out.print("naam:");
String invoer2 = sc.nextLine();

if (room1.guest == null) {
room1.guestst = invoer2;
System.out.println("Guest " + room1.guest + " gets room 1");
return;
} else {
System.out.println("no rom");
}

return;
}
}

class Room {
static int count;
String guest;

Room() {
guest = null;
count--;
}

Room(String newGuest) {
guest = newGuest;
count++;
}
}

class Guest {
String name;

Guest(String newName) {
name = newName;
}
}

最佳答案

首先,一家酒店有多个房间。根据您目前学到的知识,您应该使用数组来保存所有 Room 实例

Room[] rooms;

Hotel() {
rooms = new Room[4];
}

ArrayList

List<Room> rooms;

Hotel() {
rooms = new ArrayList<Room>();
}

另见:


根据您的评论更新:只需检查每个房间是否有客人,直到找到没有客人的房间(就像在现实世界中一样!)。伪:

if there is no guest in room1, then use room1;
else if there is no guest in room2, then use room2;
else if there is no guest in room3, then use room3;
else if there is no guest in room4, then use room4;
else say "sorry, no rooms left!";

顺便说一句,当您使用数组时,这在简单循环中更容易做到。

for each room, check if there is no guest in room, then use room;
if there is no room, then say "sorry, no rooms left!";

哦,当客人离开房间时,别忘了让客人 null。这将使房间符合重新使用的条件。

另见:

关于java - 如何创建一个类的不同实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3897263/

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