[英]Printing a list of values from array
每當循環結束時,我都在嘗試打印歌曲名稱和歌曲長度。 我該怎么做呢? Report+= songTitles[numSongs] + songLengths[numSongs]
嗎?
然后,我需要進行線性搜索以從播放列表中刪除歌曲。 我需要使用相同的報告字符串來讓用戶看到所有歌曲嗎? 我只需要幫助。 謝謝。
import javax.swing.JOptionPane;
public class asdf_Playlist {
public static void main(String[] args) {
final int MAX_SONGS = 106;
int totalDuration = 0;
int numSongs = 0;
boolean exitVar = false;
int i = 0;
String[] songTitles = new String[MAX_SONGS];
int[] songLengths = new int[MAX_SONGS];
while (exitVar == false && numSongs <= songTitles.length) {
do {
songTitles[numSongs] = JOptionPane.showInputDialog(null,"Enter a song name, or type -1 to exit");
if (songTitles[numSongs].equals("")) {
JOptionPane.showMessageDialog(null,"Error: Please enter a valid song name, or type -1 to exit");
} else if (songTitles[numSongs].equals("-1")) {
exitVar = true;
}
} while (songTitles[numSongs].equals(""));
do {
try {
songLengths[numSongs] = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a song length, e.g. 4."));
if (songLengths[numSongs] > 0) {
totalDuration += songLengths[numSongs];
} else {
songLengths[numSongs] = -1;
JOptionPane.showMessageDialog(null,"Error: please enter a valid song length, e.g. 4.");
}
} catch (NumberFormatException e) {
songLengths[numSongs] = -1;
JOptionPane.showMessageDialog(null, "Error: please enter a valid song length, e.g. 4.");
}
} while (songLengths[numSongs] <= 0);
boolean addMore = true;
while ((numSongs <= MAX_SONGS) && (addMore == true)) {
JOptionPane.showMessageDialog(null, "Song #" + (i+1) + ": " + songTitles[i] + " length: " + songLengths[i] + "\n");
i++;
if (songTitles[i] == null) {
addMore = false;
}
}
numSongs++;
}
}
}
我有一些建議可以使您更輕松地進行操作。
首先,您應該創建一個類來捕獲您的歌曲信息,而不要使用兩個單獨的數組。 從長遠來看,這將使您的生活更加輕松(並且是一種更好的面向對象的實踐)。 然后,您可以創建toString
方法作為該類的一部分,以格式化歌曲信息:
class Song {
private final String title;
private final int length;
public String toString() {
return title + ":" + length;
}
}
您的歌曲數組將變得更加簡單:
private Song[] songs = new Song[MAX_SONGS];
打印整個列表可以通過多種方式完成。 在Java 8之前,它通常看起來像:
for (Song song: songs)
System.out.println(song);
從Java 8發布以來,可以簡化為:
Arrays.stream(songs).forEach(System.out::println);
從數組中刪除項目並不像從集合中刪除項目那樣容易。 但這仍然不太難:
Song[] copy = new Song[MAX_SONGS];
int copiedSongs = 0;
for (Song song: songs)
if (/* condition for copying */)
copy[copiedSongs++] = song;
songs = copy;
numSongs = copiedSongs;
同樣,使用Java 8變得更加簡單:
songs = Arrays.stream(songs).filter(/*condition*/).toArray();
numSongs = songs.length;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.