由于我有不同类型的变量,例如整数和字符串,我想我需要使用ArrayList来存储所有这些数据。我可以存储所有数据,但不能显示特定类型的数据。例如,我让用户输入代码,歌曲名,专辑等,然后在单独的行中显示代码,歌曲名,专辑。
我不知道如何在单独的行中显示每个数据,但我知道如何显示所有数据。有人可以帮我吗?
package testmusic;
import java.util.ArrayList;
import java.util.Scanner;
public class MusicTest {
// Arraylist
ArrayList<Object> mylist=new ArrayList<Object>();
// declare variables
private Integer code;
private String songname;
private String singer;
private String album;
private String genre;
private PriceTest pricetest; // aggregate with PriceTest (HAS-a)
// default Constructor
public MusicTest() {};
// method for add music
void addMusicTest()
{
// Scanner
Scanner input=new Scanner(System.in);
// prompt user for how many song they want to input
System.out.println("How Many Song You Want to Add Into the System?: ");
int song=input.nextInt();
// for loop
for(int i=0;i<song;i++)
{
System.out.print("Enter Code: ");
mylistcode.add(input.nextInt());
mylist.add(input.nextLine());
System.out.print("Enter Song: ");
mylist.add(input.nextLine());
System.out.print("Enter Singer: ");
mylist.add(input.nextLine());
System.out.print("Enter Album: ");
mylist.add(input.nextLine());
System.out.print("Enter Genre: ");
mylist.add(input.nextLine());
System.out.print("Enter Cost Price: ");
mylist.add(input.nextInt());
System.out.print("Enter Sell Price: ");
mylist.add(input.nextInt());
System.out.println("DATA HAS BEEN CREATED!");
input.close();
}
} // ends of addMusicTest
// method for display
void displayMusciTest() //MY PROBLEM IS IN HERE
{
for(Object str:mylist)
{
System.out.println("Code: "+str);
System.out.println("Title: "+str);
System.out.println("Singer: "+str);
System.out.println("Album: "+str);
System.out.println("Genre: "+str);
}
}
// GETTER METHOD
public Integer getCode() {
return code;
}
public String getSongname() {
return songname;
}
public String getSinger() {
return singer;
}
public String getAlbum() {
return album;
}
public String getGenre() {
return genre;
}
public PriceTest getPricetest() {
return pricetest;
}
// SETTER METHOD
public void setCode(Integer code) {
this.code = code;
}
public void setSongname(String songname) {
this.songname = songname;
}
public void setSinger(String singer) {
this.singer = singer;
}
public void setAlbum(String album) {
this.album = album;
}
public void setGenre(String genre) {
this.genre = genre;
}
public void setPricetest(PriceTest pricetest) {
this.pricetest = pricetest;
}
}
答案 0 :(得分:1)
您似乎错过了作业的重点。您不应该尝试将所有单个项目存储到Objects的集合中,而应该拥有一个带有一组字段(例如Song
,songname
)的类(也许是singer
)等)。
然后,您有了Song
的集合,并且可以使用相同的方法来输出每一个(也许覆盖toString()
)。