繁体   English   中英

打印数组中的值列表

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM