gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:44:47 25 4
gpt4 key购买 nike

我正在努力学习 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”上

谢谢

最佳答案

只需使用数组:

// 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];

关于java - 如何将用户输入的数字添加到字符串的末尾以选择特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11494513/

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