以下方法从用户处获取starRating
并搜索数组以匹配该评级。当值与其中一个对象匹配时,它应该返回它。虽然该方法有效但它只返回它找到的一个Movie
对象,而不是每一个对象。例如,如果我输入3,则返回第一部星级为3的电影,然后不做任何事情。如果星级不存在,我该如何返回空列表?我做了一些研究,似乎无法找到任何有用的东西。感谢。
/**
* Write a method that returns a list of movies with the given star rating.
* Return an empty list if the star rating does not exist.
*/
public Movie getMoviesWithRating(int rating)
{
for (Movie movies : movies){
if(movies.getStarRating() == rating){
return movies;
}
}
return //EmptyList
}
答案 0 :(得分:1)
如果你有Java 8,你可以这样做:
public List<Movie> getMoviesWithRating(int rating) {
return movies.stream().filter(movie -> movie.rating == rating).collect(Collectors.toList());
}
答案 1 :(得分:0)
您必须具有返回类型的列表才能返回电影列表。
public List<Movie> getMoviesWithRating(int rating)
{
List<Movie> movies = new ArrayList<Movie>();
for (Movie movies : movies){
if(movies.getStarRating() == rating){
movies.add(movie);
}
}
return movies.
}
如果您无法更改返回类型,那么如果找不到具有给定评级的电影,则在leat返回空值。
public Movie getMoviesWithRating(int rating)
{
for (Movie movies : movies){
if(movies.getStarRating() == rating){
return movie;
}
}
return null.
}
答案 2 :(得分:0)
您可以尝试以下内容:
public List<Movie> getMoviesWithRating(int rating)
{
List<Movie> movies = new ArrayList<Movie>();
for (Movie movies : movies){
if(movies.getStarRating() == rating){
movies.add(movie);
}
}
return movies.
}
如果您正在使用Java 8
,可以尝试:
public List<Movie> getMoviesWithRating(int rating) {
return movies.stream().filter(movie -> movie.rating == rating).collect(Collectors.toList());
}
如果没有找到任何项目,更好的方法可能是抛出exception
:
public Movie getMoviesWithRating(int rating){
for(final Movie movie : Movie){
if (movie.getRating() == rating) {
return movie;
}
}
throw new NoSuchElementException();
}
答案 3 :(得分:-1)
这可能会帮助你建立自己的逻辑。谢谢..希望最好:)
public ArrayList<Movie> getMoviesWithRating(int rating)
{
ArrayList<Movie> obj_arrMovie = new ArrayList<Movie>();
for (Movie obj_movies : movies){ //Iterate throughout the movies Array.
if(obj_movies.getStarRating() == rating){ //Conditional Statement to check whether it is equivalent to rating or not ?.
obj_arrMovie.add(obj_movies); //Add all movie object to arraylist which can pass the condition.
}
}
return obj_arrMovie;
}