如何制作一个类的不同实例?

sja*_*aak 1 java

我正在制作一个简单的程序,允许人们签到和出酒店(我的CS班).

我需要做的是检查房间里的人.有四个房间.我怎样才能做到这一点,当有人办理登机手续时,下一个办理登机手续的人将在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 7

首先,酒店有一个以上的房间.根据您到目前为止所学到的内容,您应该使用数组来保存所有Room实例

Room[] rooms;

Hotel() {
    rooms = new Room[4];
}
Run Code Online (Sandbox Code Playgroud)

或者 ArrayList

List<Room> rooms;

Hotel() {
    rooms = new ArrayList<Room>();
}
Run Code Online (Sandbox Code Playgroud)

也可以看看:


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

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!";
Run Code Online (Sandbox Code Playgroud)

当您使用数组时,这在简单的循环中更容易做到.

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!";
Run Code Online (Sandbox Code Playgroud)

哦,null当他/她离开房间时别忘了让客人.这将使房间有资格重复使用.

也可以看看:

  • @ext:真的,我们可以将所有的丑陋抽象得更远,但我觉得这对初学者来说有点太复杂了:) (2认同)