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?

Recommended Answers

All 5 Replies

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();
  }
}

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
   }
}

try - catch - finally up to Java6, in Java7 try - finally

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 ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.