创建每个元素都有几个参数的数组

时间:2015-05-27 10:32:54

标签: java generics arraylist collections

我需要创建数组/ arraylist(不知道在这种情况下哪个更好),其中数组的每个元素都有3个参数。 它必须是一系列歌曲(元素),每首歌必须有这三个参数(标题,名称,持续时间)。之后我需要计算每首歌的所有持续时间。

addSong方法中,我想创建一个将成为ArrayList的1个元素的数组,但它不能正常工作。感谢帮助。

public class Jukebox extends Song {
    public ArrayList<String> songs = new ArrayList<String>();
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    public void addSong() throws IOException {
        String[] array = new String[3];

        System.out.println("Composer:");
        array[0] = reader.readLine();

        System.out.println("Title");
        array[1] = reader.readLine();

        System.out.println("Duration");
        array[2] = reader.readLine();

        ArrayList<String>songs = new ArrayList<String>(Arrays.asList(array));
        this.songs = songs;

        //Song newSong = new Song();
        //System.out.println("Composer: ");
        //newSong.composer = reader.readLine();

        //System.out.println(" Title: ");
        //newSong.title=reader.readLine();

        //System.out.println(" Duration: ");
        //newSong.duration = Double.parseDouble(reader.readLine());

        //songs.add(newSong);

    }

    public void playAll() {
        for (int i = 0; i < songs.size(); i++) {
            int j = songs.size() - i - 1;
            System.out.print(songs.get(j) + " ");
        }
    }
}

我已经创建了课程歌曲,我只是没有在这里添加。

class Song {
    String composer;
    String title;
    double duration;

    public String getComposer() {
        return composer;
    }

    public String getTitle() {
        return title;
    }

    public double getDuration() {
        return duration;
    }

    @Override
    public String toString() {
        return title + composer + duration ;
    }
}

4 个答案:

答案 0 :(得分:0)

你能创建一个具有这三个字段并将其存储在List中的Song类吗?

答案 1 :(得分:0)

您希望创建一个包含3个字段的Song类,并将Song实例添加到ArrayList。

答案 2 :(得分:0)

创建一个Song类

public class Song{
  private String composer;
  private String title;
  private String duration; //you can even take it as Int
  //write the codes for getters and setters over here
}

然后定义一个List:

List<Song> songs=new ArrayList<Song>();

答案 3 :(得分:0)

创建一个Song类。

public class Song{
  String composer, title;
  int duration;
  public Song(String composer, String title, int duration){
    this.composer = composer;
    this.title = title;
    this.duration = duration;
   }
 // getter & setters
}

为每首歌曲创建一个Song对象

    System.out.println("Composer:");
    String composer = reader.readLine();

    System.out.println("Title");
    String title = reader.readLine();

    System.out.println("Duration");
    int duration = Integer.parseInt(reader.readLine());
    Song song = new Song(composer,title,duration);

将所有内容添加到List<Song>

//create a `ArrayList` before
List<Song> songs = new ArrayList<>();
// add songs
songs.add(song)

获得所有持续时间

int totalDuration = 0;
for(Song s : songs){
  totalDuration += s.getDuration();
}