2016-02-04 55 views
0

所以我想用Java編寫一個2D數組,它存儲歌曲的名稱和它的每個插槽中的評級。我試圖用嵌套for-each循環,但它不起作用。有沒有辦法儲存有效的歌曲?使用歌曲和評分填充2D數組

public class Jukebox 
{ 
    String[][] songList = new String[2][3]; 
    public Jukebox() 
     { 
      for (String[] row : songList) 
       { 
        for (String column : row) 
         { 
          songList[0][0] = new Jukebox("Jet Airliner"); 
          songList[0][1] = new MySong("Slide", 4); 
          songList[0][2] = new MySong("Tom Sawyer", 3); 
          songList[0][3] = new MySong("Purple Rain", 2); 
          songList[1][0] = new MySong("Sing a Song", 1); 
          songList[1][1] = new MySong("Baba O'Riley", 5); 
          songList[1][2] = new MySong("Jumper", 4); 
          songList[1][3] = new MySong("Car Wash", 3); 
          songList[2][0] = new MySong("Kung Fu Fighting", 2); 
          songList[2][1] = new MySong("Right as Rain", 4); 
          songList[2][2] = new MySong("Beat It", 5); 
          songList[2][3] = new MySong("Bust a Move", 4); 
         } 
       } 

     } 
} 

回答

0

首先,你需要解決什麼問題?不希望使用HashMap嗎?假設你有5首歌曲:

Map<String, Integer> songs = new HashMap<>(); 

//populate the map as 
songs.put("Slide", 4); 
songs.put("Purple rain", 2); 
songs.put("Jumper", 3); 

//iterate through the map as 
for (Map.Entry<String, Integer>entry : songs.entrySet()) { 
    System.out.println("Song: " + entry.getKey() + " rating: " + entry.getValue()); 
} 

希望這可以幫助你。