I'm making a guess the movie game in which i take a list of movies from a text file. I have two classes for it Game
for getting a random movie and Main
for the rest of the game. Now i thought of adding a choice for hollywood or bollywood movies by changing the text files in Game
. I take 'h' or 'b' respectively as inputs. I call the constructor of Game
with parameters to choose file accordingly but it doesn't work and ALWAYS the file is null
and showing NullPointerException
.
EDIT: I am new to OOPs so please bear with me. I just saw during debugging that the debugger first goes to the class fields and THEN to the constructor, I was actually trying to use file
(which is inside the constructor) for the initialization of other fields because of which its value was null
and was showing NullPointerException
.
Now my question really remains how to use file
and noOfMovies
to initialize other fields in Game
.
//showing the setter method that i tried
//Main class
/*only showing the part having Game class*/
//making an object of Game class to get a random movie from the file
System.out.println("Enter 'h' for hollywood and 'b' for bollywood ");
Scanner input = new Scanner(System.in);
char genre = input.next().charAt(0);
Game newGame = new Game(genre);
//Game class
public class Game
{
public Game(char genre)
{
setMovieList(genre);
}
File file;
int noOfMovies;
public void setMovieList(char genre)
{
if(genre == 'h')
{
this.file = new File("C:\\Users\\Rashim\\Desktop\\java\\GuessTheMovie\\src\\hollywoodMovies.txt");
this.noOfMovies = 30;
}
else if(genre == 'b')
{
this.file = new File("C:\\Users\\Rashim\\Desktop\\java\\GuessTheMovie\\src\\bollywoodMovies.txt");
this.noOfMovies = 20;
}
// EDIT ------> I want to initialize the below fields <-------
private Scanner scan = new Scanner(this.file);
private int lineCount = 0;
int random = (int)(Math.random()*noOfMovies)+1;
//array for storing the movie titles
private String[] movieArray = new String[noOfMovies];
}