Hi I have been trying to make my first game for a while but have run into difficulty. I want to pull a randomized String from an array of Strings and then print it out but I have errors in my code. I have looked all over but I can't find the solution. Here is the code: (I have already declared the currentRoom varible)
int currentRoom;
String [][] rooms = {{"Start", "Treasure Room1"}, {"Goblin Home1", "Spider Nest1"}};
Random rand = new Random()
currentRoom = rooms [rand.nextInt( rooms.length)];
System.out.println(currentRoom);
I have an error on my currentRoom variable in line 6 and I think that is messing everything up, but I don't know so the mistake could be anywhere.
Any help is appreciated:)
3 Answers 3
Two things you have to change:
- currentRoom should be String Array
Printing string array should be done using Arrays.toString
String[] currentRoom; String [][] rooms = {{"Start", "Treasure Room1"}, {"Goblin Home1", "Spider Nest1"}}; Random rand = new Random(); currentRoom = rooms [rand.nextInt(rooms.length)]; System.out.println(Arrays.toString(currentRoom));
Sample Output
[Goblin Home1, Spider Nest1]
Hope this helps!
1 Comment
Why do you need a 2D array of strings? I think you can manage with a 1D array instead.
String currentRoom;
String[] rooms = {"Start", "Treasure Room1", "Goblin Home1", "Spider Nest1"};
Random rand = new Random();
currentRoom = rooms [rand.nextInt( rooms.length)];
System.out.println(currentRoom);
1 Comment
String currentRoom;
String [][] rooms = {{"Start", "Treasure Room1"}, {"Goblin Home1", "Spider Nest1"}};
Random rand = new Random();
int rnd = rand.nextInt( rooms.length);
currentRoom = rooms [rnd][0] + ":"+ rooms [rnd][1];
System.out.println(currentRoom);