Your problem is here:
File file = new File(fileName);
This statement is outside your constructor.
Runs until the constructor starts. Therefore, the file object is created with the wrong name (by default!)! (see here for further reading)
The best approach here: create final fields and use the "telescope constructor"; eg:
private final String fileName; private final Scanner scanner; public FileDisplay() { this("default.txt"); } public FileDisplay(String fileName) { this.fileName = fileName; this.scanner = new Scanner(new File(fileName)); }
And now the compiler helps to make sure that your fields are initialized exactly once, in the order in which you put it once in your constructor. And you have the opportunity to create a FileDisplay object using some default file name (where, in fact, I would recommend not to do this).
source share