只是想知道如何创建歌曲对象(song1,song2,song3,song4)的播放列表,其中每个对象都有自己的值(名称,艺术家,文件大小,持续时间)。我无法为此程序使用数组/列表。只需查看下面的getSong()
和addSongToPlaylist()
方法,我就会包含其他方法,以显示歌曲对象的结构。
这是我的SongDatabase类:
public class SongDatabase {
Scanner console = new Scanner(System.in);
private Song song1=null, song2=null, song3=null, song4=null;
public void addNewSong() {
if (song1 == null) {
song1 = getFromUser();
}
else if (song2 == null) {
song2 = getFromUser();
}
else if (song3 == null) {
song3 = getFromUser();
}
else if (song4 == null) {
song4 = getFromUser();
}
else {
System.out.println("The database is currently full. Please delete a song before adding a new one.");
System.out.println("");
}
}
private Song getFromUser() {
Song song = new Song();
System.out.println("Name of song:");
song.setName(console.next());
System.out.println("Artist:");
song.setArtist(console.next());
System.out.println("File size (MB):");
song.setFileSize(console.nextInt());
System.out.println("Duration (seconds):");
song.setDuration(console.nextInt());
System.out.println("Song successfully added."); /
System.out.println("");
return song;
}
public Song getSong(int songNumber) {
if (songNumber == 1){
return song1;
}
else if (songNumber == 2){
return song2;
}
else if (songNumber == 3){
return song3;
}
else if (songNumber == 4){
return song4;
}
else {
return song1;
}
}
然后我的菜单类:
public class Menu {
Scanner console = new Scanner(System.in);
private SongDatabase database = new SongDatabase();
private Playlist playlist = new Playlist();
private int songCount=0;
private void addSongToPlaylist() {
if (songCount <=3) {
System.out.println("Please enter the number of the song you'd like to be added to the playlist.");
System.out.println("");
int songNumber;
songNumber = console.nextInt();
switch (songNumber) {
case 1:
playlist.setSong(database.getSong(1));
break;
case 2:
playlist.setSong(database.getSong(2));
break;
case 3:
playlist.setSong(database.getSong(3));
break;
case 4:
playlist.setSong(database.getSong(4));
break;
default:
System.out.println("Please enter a valid song number.");
break;
}
songCount++;
}
到目前为止,addSongToPlaylist()
方法应该从getSong()
方法获取song1对象吗?但我不确定如何将这些歌曲对象添加到Playlist
类的播放列表中。我知道我需要像public void setSong(parameters?)
这样的方法,但我不确定如何构建它。有任何想法吗?非常感谢帮助,谢谢!
答案 0 :(得分:1)
如果您无法使用List
或Array
,并且PlayList
限制为3 Songs
,那么您可以尝试这样做
public class Playlist {
private Song firstSong;
private Song secondSong;
private Song thirdSong;
public void setSong(Song song) {
if (song != null) {
if (firstSong == null) {
firstSong = song;
} else if (secondSong == null) {
secondSong = song;
} else if (thirdSong == null) {
thirdSong = song;
}
}
}
}
答案 1 :(得分:0)
您可以使用任何数据结构来保存歌曲列表,例如数组,列表,集合,地图等。
下面的是使用列表的示例代码。
class PlayList {
List<Song> songList = new ArrayList<Song>();
void addSongInList(Song song){
songList.add(song)l
}
}