目标:如果有空间可以添加,则将新的 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 数组被打印出来时,新条目打印为null,即使创建的Movie 对象会在路外打印得很好。因此,我假设将 addMe 对象添加到数组中的最佳方法是创建在数组中初始化的第二个新 Movie 对象并逐个构建它(因此 addMe 将保留在内存中,并且 addMe 的“副本”将被设置到数组中)。
这对我来说感觉不是很有效(我讨厌额外的数据......)。有一个更好的方法吗?
注意:Movie 对象实际上有 10 个私有数据成员。对于这个练习,我只需要传入两个参数并为其余参数设置默认值。你可以想象为什么我不使用十个 GET 语句来构建这个数组并让额外的对象卡在内存中......
编辑:当前打印输出(部分):
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
=============================================================================
更多编辑:构造函数和设置器代码 - 所有这些都应该正常工作。
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;
}