-4

Here is a peace of code that I wrote:

double value;
String fileName;
Scanner readFile;

Scanner reader=new Scanner(System.in);
System.out.println("Enter a file name:");
fileName=reader.next();
reader.close();
try{
    readFile=new Scanner(new FileReader(fileName));
    value=readFile.nextDouble();
    readFile.close();
}
catch(FileNotFoundException e){
    System.err.println("\n The file doen't exist");
}

Then in the Catch block I want to ask the user for a valid file name an infinite times til he enters one. And if he enters an invalid file name again use a Try-Catch to throw an equal exception. How can i do it? Thanks

4
  • It's not at all clear what you mean by "use a Try-Catch to throw an equal exception". Perhaps you want a do/while loop?
    – Jon Skeet
    Jun 25, 2014 at 13:24
  • 1
    I would go for the do/while loop too. do { // your stuff } while (value not ok);
    – Jerome
    Jun 25, 2014 at 13:25
  • 1
    put it in infinite loop , if every thing works fine in try block last statement should be System.exit(0);
    – LMK
    Jun 25, 2014 at 13:25
  • This question appears to be off-topic because it lacks research effort.
    – Unihedron
    Jun 25, 2014 at 13:28

2 Answers 2

3
  • First, reuse the Scanner (don't close it right away - but do close it when it's time to).
  • Then, use an infinite loop (i.e. while (true)) to check the user input indefinitely
  • Then, initialize a new File (declare it before the loop, initialize it within the loop) with the given String, and check:
    • Whether it exists
    • Whether your program has the appropriate access rights (see File API)
  • If so, use a break statement to exit the loop

Once you have your File, you can close the Scanner (or reuse it for something else).

You may also want to enable the user to type a "quit" command to exit the loop without proceeding, as well as notifying the user if the file does not exist / is inaccessible.

1
  • Why use an infinite loop instead of while( !(file = new File( reader.next() ).exists()) )? For this case it would be more stable for the code to check for an abstract file name's existence rather than catching an exception.
    – Unihedron
    Jun 25, 2014 at 13:32
1

You missing a concept of loop in your application.

When you application expect to repeat some behavior/action. You should enclose that inside a loop. There are two loops available a for and while.

The for loop is used when the number of operation is well know before and you use an iterator for operations.

The while loop is used when you do not know when some action will occur and you just wait.

boolean shouldRetry = true;

while(shouldRetry) {

     try {
        action(); 
        shouldRetry= false;
      } catch(Exception e) {
        shouldRetry= true;                
      }
}

In your case a do while loop is required as you do not know when user will provide valid input data. At is sure that the operation should be performed at least once.

 boolean shouldRetry= false;

 do {

  try {
    action(); 
    shouldRetry= false;
  } catch(Exception e) {
    shouldRetry= true;                
  }

 }while(shouldRetry)

The condition has to be a Boolean expression. Its determine should the action be performed.

EDIT:

You should try to separate the actions in your code to separate methods if possible.

      Scanner reader = new Scanner(System.in);

      do {
          System.out.println("Enter a file name:");
      } while(!processFile(reader.next())); //Read the file name

      reader.close();


   /**
     * @return true if file read with success otherwise false.
     */
    private boolean processFile(String fileName) {

        try {
            //read the file
        }catch(Exception e) {
            return false;
        }
        return true;

    }

This give you more flexible behaviour. With this you can retry when file is not valid not only because it does not exists but also could be that it does not have the value you expect to have.

2
  • Oh true! Sorry for that.
    – Unihedron
    Jun 25, 2014 at 13:48
  • Thanks for the help. I thought that the loop would be into the catch block. That was my doubt.
    – user3775285
    Jun 25, 2014 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.