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.
Any help is appreciated:)
2 Answers 2
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.
Comments
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"]
.
Thus you have to pass 2 indexes.
Dasblinkenlight's solution seems to be the best.