[英]Program only outputting last element in array list - Java
我目前遇到一個問題,當我將數組輸出到有序列表中時,它僅輸出五首收藏中的最后一首歌曲。 我將如何使它顯示所有五個方面的任何幫助將不勝感激。 (第一次嘗試使用數組)。
private void initActionPerformed(java.awt.event.ActionEvent evt) {
ArrayList songTitle = new ArrayList();
Collections.addAll(songTitle, "Pink Floyd - The Dark Side of the Moon", "AC/DC - Back in Black", "Led Zeppelin - Led Zeppelin IV", "Billy Joel - Piano Man", "Eric Clapton - Unplugged");
Collections.sort(songTitle);
for (int j = 0; j < songTitle.size(); j++) {
nameOutput.setText(j + "- " + songTitle.get(j));
}
}
您在這里使用setText覆蓋
for (int j = 0; j < songTitle.size(); j++) {
nameOutput.setText(j + "- " + songTitle.get(j));
}
首先追加字符串,然后設置為nameOutput
。
您正在正確使用數組,但是每次循環時似乎都覆蓋了nameOutput
的內容。
我相信您期望這樣的事情。 ?
StringBuilder sb = new StringBuilder();
sb.append("");
for (int j = 0; j < songTitle.size(); j++) {
sb.append(j);
sb.append("- ");
sb.append(songTitle.get(j));
sb.append(" ");
}
nameOutput.setText(sb.toString());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.