File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

file name loop

 
John Powell
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4632
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
John Powell
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1392
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. It's finally starting to make sense.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic