This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
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 The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "file name loop" Watch "file name loop" New topic
Author

file name loop

John Powell
Greenhorn

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
System.in));
String filename = null;

do{
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
Greenhorn

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.


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

Joined: Nov 13, 2004
Posts: 11
Thank you. It's finally starting to make sense.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: file name loop