all! I'm having an issue with Scanner/passing a text file as the parameter for a method. If I create a Scanner in main, I can do everything just fine.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class App {
public static void main(String[] args){
File file = new File([FILEPATH]);
Scanner inputFile = new Scanner(file);
...
However, when I try to pass the text file to a method and create a Scanner there, I get a FileNotFoundException
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class App {
public static void main(String[] args){
File file = new File([FILEPATH]);
method(file);
}
public static String method(File file){
Scanner inputFile = new Scanner(file); //This is where I get the error :(
...
The prompt for the problem specifically says that the parameter must be a file, so I can't change it to a String parameter to pass the file path instead.
I used .getPath() to make sure the file path for the file within my method matches the file path for the file in main, and it does. I'm not sure what needs to be fixed. Would greatly appreciate any help!
EDIT; Adding screenshots with my full code and output from each version so people can verify my changes.
Did you read the error message carefully?
It doesn't say "file not found" - it says: "Unresolved compilation problem: Unhandled exception type FileNotFoundException".
This is because
new Scanner(file)is declared to throw aFileNotFoundExceptionand yourmethod()must either handle that exception or declare that it possibly throws aFileNotFoundException(by declaring it asmethod(File file) throws FileNotFoundException {...}Note that declaring the method as
method(File file) throws FileNotFoundException {...}delegates the obligation to either handle the exception or declare it as thrown exception to the caller ofmethod(). That means that in turn yourmain()method has to either handle theFileNotFoundExceptionor you need to declare yourmain()method asor
or
Why does the compiler not complain for version that works?
This is because in the version that works you declared the
main()method aspublic static void main(String[] args) throws Exception {}- the Java compiler is happy with that: that declaration tells it that any Exception thrown within the body ofmain()is acceptable.