目標:如果有空間需要添加新Movie對象到現有Movie []。將對象添加到對象陣列
代碼:
// Create the new Movie object
Movie movieToAdd = new Movie (newTitle, newYear);
// Add it to the Array
count = addMovie(movieList, movieToAdd, count);
方法代碼:
public static int addMovie (Movie[] movieArray, Movie addMe, int count)
{
if (count != movieArray.length)
{
count++;
movieArray[count] = addMe;
System.out.println("Movie added successfully!");
}
else
{
System.out.println("Array size of " + movieArray.length + " is full. Could not add movie.");
}
return count;
}
問: 目前,當movieList陣列打印出來,新的條目將打印爲空,即使創建Movie對象將打印在路外很好。因此,我假定將addMe對象添加到數組中的最佳方式是創建第二個在數組中初始化的新Movie對象,並逐個構建它(所以addMe將保留在內存中,並且addMe的「副本」將被設置到數組中)。
這對我來說並不覺得很有效(我討厭額外的數據鋪設...)。有一個更好的方法嗎?
注意:Movie對象實際上有10個私有數據成員。對於這個練習,我只需要傳入兩個參數併爲其餘的設置默認值。你能想象我爲什麼不使用十條送語句來建立這個數組,並有停留在記憶額外的對象......
編輯: 當前打印輸出(部分):
Menu options:
1. Show all movies:
2. Show movies sorted - manual
3. Show movies sorted - auto
4. Show Movie by Index
5. Search for movie Linearly
6. Search for movie using Binary Search
7. Add a movie
20. Quit
Please choose an option from the menu: 1 to 20:
7
Let's add the information for the new movie. Give me a Title and 4-digit Year, and I'll fill in the rest.
Title?
Me
Year of Release?
Please enter a valid 4 digit year: 1000 to 9999:
1213
Movie added successfully!
Menu options:
1. Show all movies:
2. Show movies sorted - manual
3. Show movies sorted - auto
4. Show Movie by Index
5. Search for movie Linearly
6. Search for movie using Binary Search
7. Add a movie
20. Quit
Please choose an option from the menu: 1 to 20:
25 | Les Vampires (1915) | Louis Feuillade | "Edouard Mathe, Marcel Levesque" | 1915 | 0 | http://www.imdb.com/title/tt0006206/ | http://www.guardian.co.uk/film/movie/117077/vampires | France | Horror | 175
null | 176
=============================================================================
多個編輯: 構造函數和Setter代碼 - 所有這些都應該正常工作。
public Movie (String t, int y)
{
// passed in
this.title = setTitle(t);
this.year = setYear(y);
// defaults
this.ranking = 0;
this.director = "No Director";
this.actors = "No Actors";
this.oscars = 0;
this.linkIMDB = "No IMDB Link";
this.linkGuardian = "No Guardian Link";
this.country = "No Country";
this.genre = "No Genre";
}
public String setTitle (String newTitle)
{
if (newTitle == null)
{
this.title = "No Title";
}
else
{
this.title = newTitle;
}
return this.title;
}
public int setYear (int newYear)
{
if (newYear >= 999 && newYear <=10000)
{
this.year = newYear;
}
else
{
newYear = 0000;
}
return this.year;
}
_「當movieList陣列打印出來,新的條目將打印爲空」 _什麼?哪裏?怎麼樣?這段代碼看起來很好。 –
這不是C#嗎? –
Yuriy'System.out。println'是一個很好的提示;) – Rogue