try {
dataFile = args[0];
}

catch (Exception e) {
System.out.println("The file was not found. Please input file name now: ");
dataFile = scan.nextLine();
}

This gets a file name from the command line, and if no file is specified it asks the user to input a file name, however, it only asks once. If no valid file name is inputted it produces an error message. What code should I use to loop this so it will repeatedly ask the user to input a file until he/she inputs a valid file name?

On way to do it is to put the whole thing in a method. If it throws an exception, call the method again...

public void tryFile() {
  System.out.print("Enter file name: ");
  try { dataFile = scan.nextLine(); }  // assume that scan is the class variable
  catch (Exception e) {
    System.out.println("The file was not found. Please input file name now: ");
    tryFile();
  }
}

Edited 5 Years Ago by Taywin: n/a

Heeding your advice, I wrote this:

// start main method with necessary variables
try {
	dataFile = args[0];
}

catch (Exception e) {
	dataFile = fileNotFound();
}
// end of main method

public static String fileNotFound() {

	String fileName = "";
	Scanner scan = new Scanner(System.in);
	System.out.println("The file was not found. Please input file name now: ");

	try {
		fileName = scan.nextLine();
	} catch (Exception e) {
		fileNotFound();
	}

	return fileName;

	}

Yet, I still receive the FileNotFoundException after the first prompt.

You would normally use a template something like this:

String fileName = "";
while (fileName.equals("")) {
   try {
      // get the file name - if successful fileName will not be ""
   } catch(...) {
      // do error message
      fileName = ""; // force it round the loop again
   }
}

The code you are trying is wrong ...

Try checking file exists if not ask the user to type the file name again .. it is very simple .. why you need to create an exception for this ?

This article has been dead for over six months. Start a new discussion instead.