1

我正在为一些 Java 代码而苦苦挣扎。

目前我有8个房间

    room1 = new Room(1,1);
    room2 = new Room(2,1);
    room3 = new Room(3,1);
    room4 = new Room(4,1);
    room5 = new Room(5,2);
    room6 = new Room(6,2);
    room7 = new Room(7,3);
    room8 = new Room(8,3);

现在我需要让用户输入关于他们需要的房间的数字 1 到 8,然后系统需要将该数字添加到前缀房间,以便我可以调用所需房间的方法。

我目前有这个代码来接收选择

roomselect = scan.nextInt();

然后这就是我卡住的地方,因为我不确定如何将 roomselect 整数添加到前缀“房间”上

谢谢

4

4 回答 4

2

只需使用数组:

// Create an array of Rooms
Room rooms[] = new Room[8];
// Now, you have a placeholder for 8 rooms
// Know that it are simply placeholders, the rooms are not initialized.
// Each element of the array is initialized to null

// Assigning
rooms[2] = new Room(3, 2); // Initialize the room at index 2 (which is the 3th 
                           // in spoken language)


// Retrieving
int index = 4; // Indices start at 0
Room room4 = rooms[index];

// Or...
rooms[5].doSomething();


// Getting the length
int numberOfRooms = rooms.length;

因此,要解决您的问题:

int roomselect = scan.nextInt();
Room selectedRoom = rooms[roomselect];
于 2012-07-15T18:33:46.827 回答
1

如果您将代码更改为:

List<Room> rooms = new ArrayList<Room>();    
rooms.add(new Room(1,1));
rooms.add(new Room(2,1));
...

你可以得到你指定的房间

rooms.get(roomselect);

请注意,索引将从 0 开始,而不是从 1 开始。

于 2012-07-15T18:33:55.797 回答
1

将您的房间存储在一个数组中,而不是作为单独的变量,然后通过数组索引访问每个房间:

Room[] rooms = new Room[8];

rooms[roomNumber].doSomething();
于 2012-07-15T18:34:16.077 回答
0

Java 集合就是答案...

ArrayList<Room> room = new ArrayList<Room>();

Scanner scan = new Scanner(System.in);

for (int i=1 ; i<9 ; i++){

     int r = scan.nextLine();

     if (r<5){

       room.add(new Room(r,1));
   }

    else if ((r>4) && (r<7)){

      room.add(new Room(r,2));
   }

    else if (r>6){

       room.add(new Room(r,3));

   }

}
于 2012-07-15T18:43:03.483 回答