Is there a way to use a try/catch statement to ask the user to enter a file, if the user enters the wrong filename, the program will ask two more times, and then exit with an exception? How could I loop? Because once the user enters the wrong filename the program throws the exception immediately.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
static String[] words = new String[5];
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("enter file name:");
String fileName = kb.next();
try {
File inFile = new File(fileName);
Scanner in = new Scanner(new File(fileName));
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
I hope it’s obvious that the FileNotFoundException is thrown by the Scanner constructor. So why use it until you’re sure the file exists? You shouldn’t create the Scanner object till you got the correct file!
To implement this idea use this in your try block: