Error while instantiating in Java

Asked

Viewed 56 times

1

In my course on Java OO, I have assembled a class to perform certain functions. But always return Nullpointexception. If I do the same thing main, without creating any class, everything works in a good.

What am I doing wrong?

Chunk that error using the class I created:

public class Main {

    public static void main(String[] args) throws FileNotFoundException {
    // write your code here

        Movie movie = new Movie();
        movie.setMovieFile("movies.txt");

        System.out.println(movie.getMovieListSize());
    }
}

If I do the same thing inside Main()

public class Main {

    public static void main(String[] args) throws FileNotFoundException {
    // write your code here

       File file = new File("movies.txt");
       Scanner scanner = new Scanner(file);

       if (scanner.hasNextLine()){
           System.out.println(scanner.nextLine());
       }
    }
}

And this is the class I wrote and every object returns error:

public class Movie {

   private List<String> movies;
   private File file;
   private Scanner scanner;
   private boolean hasSetted;

    public Movie() {
    }

    public void setMovieFile(String movieFile) throws FileNotFoundException {
        file = new File(movieFile);
        scanner = new Scanner(file);

        while (scanner.hasNextLine()){
            movies.add(scanner.nextLine());
        }

        hasSetted = true;
    }

    public String getMovie(int position){
        return movies.get(position);
    }

    public int getMovieListSize(){
        return movies.size();
    }

}

That code is on github tbm: https://github.com/sshnakamoto/MovieGuess

  • nullpointer on which line?

  • 4

    You didn’t start the field movies, shall do so at the builder.

  • 1

    Lacked instantiation movies. He is only declared

1 answer

7


The variable movies has never been instantiated, so you are trying to add a movie to a null variable and not to an empty list.

Install the list correctly, I suggest you do it in the constructor:

public Movie() {
   movies = new ArrayLis<>();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.