• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

file name loop

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
John Powell
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you. It's finally starting to make sense.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic