gpt4 book ai didi

Java 空构造函数

转载 作者:行者123 更新时间:2023-11-30 02:25:18 24 4
gpt4 key购买 nike

所以我有两个类,称为歌曲和专辑,它们是:

    public class Songs {
private String title;
private Double duration;

public Songs(String title, Double duration) {
this.title = title;
this.duration = duration;
}

public Songs(){}


public String getTitle() {
return title;
}



public Double getDuration() {
return duration;
}


public static Songs addSong(String title, Double duration){
return new Songs(title,duration);

}
}



import java.util.ArrayList;
import java.util.LinkedList;

public class Albums {
private ArrayList<Songs> albums;
private String name;
private String title;

public Albums(String name, String title) {
this.albums = new ArrayList<>();
this.name = name;
this.title = title;
}

public boolean addSong(Songs songs){
if(findSong(songs.getTitle())==null){
this.albums.add(songs);
return true;
}else{
System.out.println("Song alredy exist!");
return false;
}

}

private Songs findSong(String songName){
for(int i=0;i<this.albums.size();i++){
Songs currentSong = this.albums.get(i);
if(currentSong.equals(songName)){
return currentSong;
}
}
return null;
}
}

问题是主要的,也许我的逻辑不对,如果我遗漏了什么,请告诉我:

 public class Main {

public static void main(String[] args) {
Albums albums = new Albums("Alexandru", "Doi dsadcopii");
Songs songs = new Songs("Patrascu",4.44);
songs.addSong("Dorin",11.11);
albums.addSong(songs);

songs.addSong("Dorin",11.11);
albums.addSong(songs);


songs.addSong("Dorinsads",11.11);
albums.addSong(songs);


songs.addSong("Dorisadsan",11.11);
albums.addSong(songs);



System.out.println(songs.getTitle());

albums.addSong(songs);

albums.printSongs();
}
}

为什么我得到相同的值?为什么 .addSong 中的那些值没有添加到列表中?这是我打印列表的代码:

    public void  printSongs() {
for (int i = 0; i < this.albums.size(); i++) {
System.out.println(i + 1 + "-->" + this.albums.get(i).getTitle() + "--->" + this.albums.get(i).getDuration());
}

}

确实我遗漏了一些东西,但我不知 Prop 体在哪里,有什么想法可以解决这个问题吗?谢谢! :D问题是当我使用 .printSongs() 方法时它会打印第一个值

最佳答案

来自类(class)的歌曲:

public static Songs addSong(String title, Double duration){
return new Songs(title,duration);
}

这只是返回一首新歌曲,而不是将其添加到内部列表中。

您可以直接将它们添加到相册中,例如

Albums albums = new Albums("Alexandru", "Doi dsadcopii");
albums.addSong(new Songs("Patrascu",4.44));
albums.addSong(new Songs("Dorin",11.11));

关于Java 空构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45770183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com