• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Input from console, writing to file

 
Geir Johnsen
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all!

I am trying to read input from the console, and write it to a file. I
The thought was that the user terminates the program by simply not typing any text, just hitting enter.. I was thinking a do-/while loop could do the trick..

Anyway, here's what I got so far:




This code gives me the error:

cannot find symbol
symbol : variable fromConsole
location: class TestJava2
while (fromConsole.lenth() > 0);



Any comments on this? I have no problem setting up writing one line at a time, but it is creating the loop that gives me the problem.
I would really appreciate any help.

Geir.
 
Neha Daga
Ranch Hand
Posts: 504
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thats because you have declared the string variable fromconsole within the do loop which can not be seen outside do loop. So when your while loop condition uses fromconsole it cannot find that.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this
 
Geir Johnsen
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you both for your reply

I got it working using the following code:



But can someone explain to me why the following line is needed:


If it is removed, nothing is written to the file..

Br
Geir
 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the close() call ought to be in a finally block. It is there to make sure the Writer and the connection to the file are closed. Otherwise, that file may be inaccessible to other code.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic