如何将用户输入编号添加到字符串的末尾以选择特定对象

时间:2012-07-15 18:30:51

标签: java

我正在努力解决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整数添加到前缀'room'

感谢

4 个答案:

答案 0 :(得分: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];

答案 1 :(得分:1)

如果您将代码更改为:

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

你可以通过

获得指定的房间
rooms.get(roomselect);

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

答案 2 :(得分:1)

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

Room[] rooms = new Room[8];

rooms[roomNumber].doSomething();

答案 3 :(得分:0)

Java Collection 就是答案......

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));

   }

}