所以我试图用Java编写一个2D数组,在每个插槽中存储歌曲名称及其评级。我已尝试使用嵌套for-each循环执行此操作,但它不起作用。有没有办法存储有效的歌曲?
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 :(得分: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());
}
希望这会对你有所帮助。