我正在尝试创建一个允许用户输入有关电影的信息的数组
public void addMovie() {
for(int x = 0; x < mlist.length; x++) {
mlist[x] = new Movies();
System.out.println("What is the title of the movie? ");
title = scan.nextLine();
System.out.println("What is the genre of the movie? ");
genre = scan.nextLine();
System.out.println("Who is the director of the movie? ");
director = scan.nextLine();
System.out.println("What is the cost of the movie? ");
cost = scan.nextInt();
}
}
当我编译时,它说
mlist[x] = new Movies();
构造函数类电影中的电影无法应用于给定类型;
完整代码:
import java.util.Scanner;
public class Movies
{
private String title, genre, director;
private int cost;
Movies mlist[] = new Movies[5];
Scanner scan = new Scanner(System.in);
public Movies(String mtitle, String mgenre, String mdirector, int mcost)
{
title = mtitle;
genre = mgenre;
director = mdirector;
cost = mcost;
}
public void addMovie()
{
for(int x = 0; x < mlist.length; x++)
{
mlist[x] = new Movies();
System.out.println("What is the title of the movie? ");
title = scan.nextLine();
System.out.println("What is the genre of the movie? ");
genre = scan.nextLine();
System.out.println("Who is the director of the movie? ");
director = scan.nextLine();
System.out.println("What is the cost of the movie? ");
cost = scan.nextInt();
}
}
public String getTitle()
{
return title;
}
public String getGenre()
{
return genre;
}
public String getDirector()
{
return director;
}
public int getCost()
{
return cost;
}
}
答案 0 :(得分:3)
在函数addMovie()中,您将从用户那里获取输入,而不是在任何地方使用它。不要调用无参数构造函数,而是调用您创建的参数化构造函数,并将输入值传递给此构造函数。
代码:
public void addMovie() {
for (int x = 0; x < mlist.length; x++) {
// Deleted the call to default constructor.
System.out.println("What is the title of the movie? ");
title = scan.nextLine();
System.out.println("What is the genre of the movie? ");
genre = scan.nextLine();
System.out.println("Who is the director of the movie? ");
director = scan.nextLine();
System.out.println("What is the cost of the movie? ");
cost = scan.nextInt();
// Added this code
mlist[x] = new Movies(title,genre,director,cost);
}
}
这应解决错误。