0

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

asked Apr 16, 2013 at 21:42

2 Answers 2

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.

answered Apr 16, 2013 at 21:44
Sign up to request clarification or add additional context in comments.

Comments

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"].

Thus you have to pass 2 indexes.

Dasblinkenlight's solution seems to be the best.

answered Apr 16, 2013 at 21:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.