Hi I was wondering how I can print out one random value of an array instead of two of them. Here is my code:
嗨,我想知道如何打印出一个数组的随机值而不是其中两个。这是我的代码:
public static void main(String args[])
{
String[] currentRoom;
String[][] rooms = new String [2] [2];
rooms [0] [0] = "Start";
rooms [0] [1] = "Treasure Room 1";
rooms [1] [0] = "Goblin Hive 1";
rooms [1] [1] = "Spider Nest";
Random rand = new Random();
{
currentRoom = rooms[rand.nextInt(rooms.length)];
System.out.println(Arrays.toString(currentRoom));
}
}
When I print it out it will say two values from my array, something like: ["Start", "Treasure Room1"] and I need it to print out just one value like: ["Start"] or just ["Spider Nest1"]. I was wondering how I can solve this.
当我打印出来时,它会说出我的数组中的两个值,例如:[“Start”,“Treasure Room1”],我需要它打印出一个值,如:[“Start”]或只是[“Spider Nest1” “。我想知道如何解决这个问题。
Any help is appreciated:)
任何帮助表示赞赏:)
2 个解决方案
#1
6
You need to generate a random index in the second dimension, like this:
您需要在第二维中生成随机索引,如下所示:
String[] currentRoomRow = rooms[rand.nextInt(rooms.length)];
String currentRoom = currentRoomRow[rand.nextInt(currentRoom.length)];
System.out.println(currentRoom);
This is OK when all rows have the same size; if they do not, the above code would "favor" items from "shorter" rows. Fixing this deficiency would require more preparation: you would need to "flatten" your array, generate a single random up to the number of items, and then pick an item from the flattened array.
当所有行具有相同的大小时,这是可以的;如果他们不这样做,上面的代码将“赞成”来自“较短”行的项目。修复此缺陷需要更多准备工作:您需要“展平”数组,生成单个随机数量的项目,然后从展平数组中选择一个项目。
#2
2
This is a two-dimensional array. By using only one index, you'll get an array (maybe with multiple values). By using rooms [0]
you'll return ["Start", "Treasure Room1"]
.
这是一个二维数组。通过仅使用一个索引,您将获得一个数组(可能具有多个值)。通过使用房间[0],您将返回[“开始”,“宝藏室1”]。
Thus you have to pass 2 indexes.
因此,您必须传递2个索引。
Dasblinkenlight's solution seems to be the best.
Dasblinkenlight的解决方案似乎是最好的。
#1
6
You need to generate a random index in the second dimension, like this:
您需要在第二维中生成随机索引,如下所示:
String[] currentRoomRow = rooms[rand.nextInt(rooms.length)];
String currentRoom = currentRoomRow[rand.nextInt(currentRoom.length)];
System.out.println(currentRoom);
This is OK when all rows have the same size; if they do not, the above code would "favor" items from "shorter" rows. Fixing this deficiency would require more preparation: you would need to "flatten" your array, generate a single random up to the number of items, and then pick an item from the flattened array.
当所有行具有相同的大小时,这是可以的;如果他们不这样做,上面的代码将“赞成”来自“较短”行的项目。修复此缺陷需要更多准备工作:您需要“展平”数组,生成单个随机数量的项目,然后从展平数组中选择一个项目。
#2
2
This is a two-dimensional array. By using only one index, you'll get an array (maybe with multiple values). By using rooms [0]
you'll return ["Start", "Treasure Room1"]
.
这是一个二维数组。通过仅使用一个索引,您将获得一个数组(可能具有多个值)。通过使用房间[0],您将返回[“开始”,“宝藏室1”]。
Thus you have to pass 2 indexes.
因此,您必须传递2个索引。
Dasblinkenlight's solution seems to be the best.
Dasblinkenlight的解决方案似乎是最好的。