這裏是你可以打一個比方。這使用列表而不是數組。您可以將列表替換爲數組,但必須在構造函數中爲數組設置大小。此外,添加陣列會產生新的問題,您將不得不處理。
AlbumInfo類:
import java.util.*;
/**
*
* @author Sedrick
*/
public class AlbumInfo {
private String albumName;
private String artist;
private List<String> tracksTitle;
private List<String> tracksLength;
public AlbumInfo()
{
albumName = "Add Album Name";
artist = "Add Artist Name";
tracksTitle = new ArrayList();
tracksLength = new ArrayList();
}
/**
* @return the albumName
*/
public String getAlbumName()
{
return albumName;
}
/**
* @param albumName the albumName to set
*/
public void setAlbumName(String albumName)
{
this.albumName = albumName;
}
/**
* @return the artist
*/
public String getArtist()
{
return artist;
}
/**
* @param artist the artist to set
*/
public void setArtist(String artist)
{
this.artist = artist;
}
/**
* @return the tracksTitle
*/
public List<String> getTracksTitle()
{
return tracksTitle;
}
/**
* @param tracksTitle the tracksTitle to set
*/
public void addTrackTitle(String trackTitle)
{
this.tracksTitle.add(trackTitle);
}
/**
* @return the tracksLength
*/
public List<String> getTracksLength()
{
return tracksLength;
}
/**
* @param tracksLength the tracksLength to set
*/
public void addTrackLength(String trackLength)
{
this.tracksLength.add(trackLength);
}
}
主要測試類:
import java.util.*;
/**
*
* @author Sedrick
*/
public class AlbumTest {
static final String[] trackTitles = {"Ambitionz Az a Ridah", "All Bout U", "Skandalouz", "Got My Mind Made Up", "How Do U Want It", "2 of Amerikaz Most Wanted", "No More Pain", "Heartz of Men", "Life Goes On", "Only God Can Judge Me", "Tradin' War Stories", "California Love(Remix)", "I Ain't Mad at Cha", "What'z Ya Phone #"};
static final String[] trackLength = {"4:39", "4:37", "4:09", "5:14", "4:47", "4:07", "6:14", "4:43", "5:02", "4:57", "5:29", "6:25", "4:53", "5:10"};
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
// Add album info
AlbumInfo allEyesOnMeDiscOne = new AlbumInfo();
allEyesOnMeDiscOne.setAlbumName("All Eyes On Me");
allEyesOnMeDiscOne.setArtist("Tupac");
for (int i = 0; i < trackTitles.length; i++) {
allEyesOnMeDiscOne.addTrackTitle(trackTitles[i]);
}
for (String entry : trackLength) {
allEyesOnMeDiscOne.addTrackLength(entry);
}
//Print album info
System.out.println("Album Name: " + allEyesOnMeDiscOne.getAlbumName());
System.out.println("Album Artist: " + allEyesOnMeDiscOne.getArtist());
List albumTitles = allEyesOnMeDiscOne.getTracksTitle();
List albumTitlesLength = allEyesOnMeDiscOne.getTracksLength();
for (int i = 0; i < albumTitles.size(); i++) {
System.out.println("Title: " + albumTitles.get(i) + " Length: " + albumTitlesLength.get(i));
}
}
}
您可以發佈您段聲明 –
這是第(字符串,字符串[],INT []) – Serkuto
我推薦使用ArrayList,但我仍然想知道爲什麼你使用課堂部分?這個類包含三個屬性,那麼問題是什麼 –