Wryen Wryen - 17 days ago 5
Java Question

Not able to initialize objects in each array index

I'm trying to create an array that lets the user input information about a movie

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();
}
}


When I compile, it says that

mlist[x] = new Movies();


constructor Movies in class Movies cannot be applied to given types;

Complete code:

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;
}
}

Answer

In the function addMovie(), you are taking input from the user and not using using it anywhere. Instead of calling a parameter-less constructor, call the parametrized constructor which you created and pass the input values to this constructor.

Code :

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);
    }
}

This should resolve the error .