I have a method called isValidFile which takes in a user input string and determines if that is a valid file. The method output is of the File type. I am able to take in 2 file names in the command line and process them properly. I am also able to take in 1 valid, and 1 invalid. The isValidFile will check validity and promt the user for a valid file name if the one entered is not correct. However, it will not work with 2 invalid inputs. I call them as follows....
String[] inLines = commandLine(args);
File reservedWords = isValidFile(inLines[0]);
File toParse = isValidFile(inLines[1]);
Here is my isValidFile method...
public static File isValidFile(String userFile){
System.out.println("START OF isValidFile");
File inFile = new File(userFile);
Scanner in = null;
while(!inFile.exists() || inFile.isDirectory()){
System.out.println("Please enter a valid file name or Q to quit.");
in = new Scanner(System.in);
String validFile = in.nextLine();
System.out.println("IS VALID FILE? " + validFile); // TEST LINE
if(validFile.equalsIgnoreCase("q")){
System.out.println("\nProgram terminated by user.");
in.close();
return null;
} else inFile = new File(validFile);
if (inFile.exists()) in.close();
}
System.out.println("END OF isValidFile\n");
return inFile;
}
You can see where I put in test lines to show the start, end, and the file name printed out if it is accepted. Here is my output. You can see that once I entered a valid file for the first argument, it asks for the file name of the 2nd argument but does not allow me to enter any information. It just throws a NoSuchElementException. Why would it work for the first call to the method and not for the second call?
START OF isValidFile
Please enter a valid file name or Q to quit.
in.txt
IS VALID FILE? in.txt
END OF isValidFile
START OF isValidFile
Please enter a valid file name or Q to quit.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Project6.isValidFile(Project6.java:53)
at Project6.main(Project6.java:9)
--- Line 53 is the line: String validFile = in.nextLine();
--- Line 9 is the line: File toParse = isValidFile(inLinse[1]);