In my course on Java OO, I've assembled a class to perform certain functions. But they always return NullPointException. If I do the same thing within the main
method, without creating any class, everything works fine.
What am I doing wrong?
Excerpt that gives 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 within 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();
}
}
This code is in github tbm: link