2013-04-15 101 views
0

嗨我一直試圖讓我的第一場比賽有一段時間,但遇到困難。我想從字符串數組中抽取一個隨機字符串,然後將其打印出來,但是我的代碼中有錯誤。我查看了所有,但我找不到解決方案。下面是代碼: (我已經宣佈currentRoom varible)如何從Java中的數組中打印出一個隨機的字符串

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

我對在第6行我currentRoom變量的錯誤,我認爲這是搞亂了一切,但我不知道這樣的錯誤可能在任何地方。

任何幫助表示讚賞:)

回答

1

兩件事情你必須改變:

  1. currentRoom應該是字符串數組
  2. 打印字符串數組以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)); 
    

樣本輸出

[Goblin Home1, Spider Nest1] 

希望這有助於!

+0

因爲以後它會更復雜 – user2280906

0
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); 
1

爲什麼你需要一個二維數組的字符串? 我想你可以使用一維數組來管理。

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); 
+0

因爲以後它會變得更復雜 – user2280906

相關問題