When ever I enter a name the file is created and the lines are there but when I use the display method, it spits out that error and I am not sure where my problem is and I'm kinda new to Java. I have a method in another class to save the lines but I don't think that is where my problem is, and I am kinda stuck, any help would be appreciated.
package X;
import java.util.Scanner;
import java.io.*;
public class FileDisplay {
String filename;
public FileDisplay(String name) {name = filename;}
public void display() throws IOException {
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()) {
String str = inputFile.nextLine();
System.out.println(str);
}
inputFile.close();
}
}
I ran the code and every time it spits out this error :
Exception in thread "main" java.lang.NullPointerException
at java.base/java.io.File.<init>(File.java:276)
at ES1036a.Lab6.FileDisplay.display(FileDisplay.java:12)
at ES1036a.Lab6.FilesDemo.main(FilesDemo.java:27)
And this is the demo class :
package X;
import java.util.Scanner;
import java.io.*;
public class FilesDemo {
public static void main(String[] args) throws IOException {
String filename = "lines.txt";
Scanner keyboard = new Scanner(System.in);
System.out.println("What's the filename?");
filename = keyboard.nextLine();
FileSave FilesDemo = new FileSave(filename);
FilesDemo.save("1-Lorem ipsum dolor sit amet\n" +
"2-Consectetuer adipiscing elit\n" +
"3-Sed diam nonummy nibh euismod tincidunt\n" +
"4-Ut wisi enim ad minim veniam\n" +
"5-Quis nostrud exerci tation ullamcorper\n" +
"6-Suscipit lobortis nisl ut aliquip ex ea commodo consequat\n" +
"7-Duis autem vel eum iriure dolor in hendrerit\n" +
"8-Vel illum dolore eu feugiat nulla facilisis at vero eros");
FileDisplay FilesDemo2 = new FileDisplay(filename);
FilesDemo2.display();
}
}
name = filename;
does?name
or infilename
?