我正在用Java做些小练习。我需要输入3部电影的三个详细信息(标题,类型和等级),然后进行显示。
因此,基本上,我必须为每个私有数据成员编写适当的getter和setter方法,并且还应该为应用程序编写适当的构造函数,该应用程序包括一个tester / driver类,该类创建Movie类的三个实例并将其存储在数组。测试人员类应使用for循环来设置Movie对象的标题,类型和等级。还应该使用for循环,该循环应遍历数组并显示数组每个元素的标题,类型和等级,并为每个对象调用playIt()方法。
到目前为止,这是我的movie.class和movieTester.class代码
public class Movie {
// Declare Private Variables
private String title;
private String genre;
private int rating;
// Default constructor
public Movie() {
}
/// The constructors ///
public Movie(String title,String genre, int rating) {
this.title = title;
this.genre = genre;
this.rating = rating;
}
// Getter and setter methods
public String getTitle() { // getTitle
return title;
}
public void setTitle(String title) { // SetTitle
this.title = title;
}
public String getGenre() { // GetGenre
return genre;
}
public void setGenre(String genre) { // SetGenre
this.genre = genre;
}
public int getRating() { // GetRating
return rating;
}
public void setRating(int rating) { // SetRating
this.rating = rating;
}
public void playIt(){
System.out.println("Playing the Movie");
}
}
这是针对MovieTester.class
import java.util.Scanner;
public class MovieTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //Create Scanner input
// Populate using an array of Movie's
Movie mymovie[] = new Movie[3];
// Using for loop
for (int i = 0; i < 3; i++) {
Movie movie = new Movie();
// Enter Details For Movie
System.out.println("Please Enter The Title Of Movie: ");
String title = input.nextLine();
movie.setTitle(title);
System.out.println("Please Enter The Genre Of Movie: ");
String genre = input.nextLine();
movie.setGenre(genre);
System.out.println("Please Enter The Rating Of Movie: ");
int ret = Integer.parseInt(input.next());
movie.setRating(ret);
System.out.println();
mymovie[i] = movie;
}
// Using for loop o traverse the.
// array and display the title, genre and rating,
// for each element of the array
for (int i = 0; i < mymovie.length; i++) {
Movie movie = mymovie[i];
System.out.println("Title: " + movie.getTitle());
System.out.println("Genre: " + movie.getGenre());
System.out.println("Rating: " + movie.getRating());
mymovie[i].playIt();
System.out.println();
}
}
}
当我运行它时,我得到的是:
Please Enter The Title Of Movie:
Harold and Kumar
Please Enter The Genre Of Movie:
Comedy
Please Enter The Rating Of Movie:
5
Please Enter The Title Of Movie:
Please Enter The Genre Of Movie:
Comedy
Please Enter The Rating Of Movie:
4
Please Enter The Title Of Movie:
Please Enter The Genre Of Movie:
Action
Please Enter The Rating Of Movie:
3
Title: Harold and Kumar
Genre: Comedy
Rating: 5
Playing the Movie
Title:
Genre: Comedy
Rating: 4
Playing the Movie
Title:
Genre: Action
Rating: 3
Playing the Movie
输出的问题是在输入第一个完整的电影详细信息(标题,流派和等级)之后。它跳过了输入电影“标题”(第二和第三)的操作,只能输入流派和等级。
“ for循环”可能存在一些问题。但是无法弄清楚。 有人可以告诉我代码有什么问题吗?