我想使用for循环向用户询问3部电影的标题,流派和评级,并将信息存储在一个数组中,然后将信息显示给他们。实例变量是私有的,使用了getter和setter但是我不知道在尝试使用for循环获取信息时如何使用MovieTestDriver类中的getter和setter。
class Movie {
// Create instance variables for the Movie class.
private String title;
private String genre;
private int rating;
// Use getters and setters to set and display the variables.
// Getters.
public String getTitle() {
return title;
}
public String getGenre() {
return genre;
}
public int getRating() {
return rating;
}
// Setters.
public void setTitle(String newTitle) {
title = newTitle;
}
public void setGenre(String newGenre) {
genre = newGenre;
}
public void setRating(int newRating) {
rating = newRating;
}
void playIt() {
System.out.println(getTitle() + "- Now Playing!");
}
}
import java.util.Scanner;
public class MovieTestDriver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Creates a Movie array of size 3.
Movie[] movies = new Movie[3];
String getTitle;
String getGenre;
int getRating;
// Allows user to enter variables 3 times and populate movie object and store them in an array.
for (int i=0; i< movies.length; i++) {
System.out.println("Please enter the title of Movie " + (i+1));
getTitle = input.nextLine();
System.out.println("Please enter the genre of Movie " + (i+1));
getGenre = input.nextLine();
System.out.println("Please enter the rating (1-5) of Movie " + (i+1));
getRaing = input.nextInt();
}
}
答案 0 :(得分:0)
使用其他方法创建电影实例。并且可以通过另一个来显示电影:)这样你的代码就会清晰可读。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Creates a Movie array of size 3.
Movie[] movies = new Movie[3];
// Allows user to enter variables 3 times and populate movie object and store them in an array.
for (int i=0; i< movies.length; i++) {
movies[i] = inputMovie(input);
}
}
private static Movie inputMovie(Scanner input){
Movie movie = new Movie();
System.out.println("Please enter the title of Movie " + (i+1));
movie.setTitle(input.nextLine());
System.out.println("Please enter the genre of Movie " + (i+1));
movie.setGenre(input.nextLine());
System.out.println("Please enter the rating (1-5) of Movie " + (i+1));
movie.setRating(input.nextInt());
return movie;
}