File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes file name loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "file name loop" Watch "file name loop" New topic

file name loop

John Powell

Joined: Nov 13, 2004
Posts: 11
I'm trying to ask the user for a file to use. If the file is found then the program continues, but if the file is not found the user is asked to enter the filename again and again until it's found. I assume I could do it with a loop, but I'm unsure of the condition to test for the file not found.

BufferedReader stdin = new BufferedReader(new InputStreamReader;
String filename = null;

System.out.print("Please enter filename: ");
filename = stdin.readLine();
}while (file is not found???)

Any ideas?
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
John Powell

Joined: Nov 13, 2004
Posts: 11
Thanks for the info.

The problem I run into now is a Null pointer exception. If I surround the loop with a try/catch it works ok, but it only runs once. I'm not sure if I'm missing something or whether there's a problem with the logic.
Joyce Lee
Ranch Hand

Joined: Jul 11, 2003
Posts: 1392
Hi John,

static File file; // class variable
File file = new File(filename); // local variable

You declared the variable file in two locations. By doing so, the local one is used within the curl brackets of do...while loop. This is called shadowing. Once it is out of curl brackets, the class variable file referencing to a null object is used.

To resolve the NullPointerException, simply remove the declaration for the local variable file.

[ November 13, 2004: Message edited by: Joyce Lee ]
John Powell

Joined: Nov 13, 2004
Posts: 11
Thank you. It's finally starting to make sense.
I agree. Here's the link:
subject: file name loop
It's not a secret anymore!