infinite loop with user input

Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Apr 2009
Posts: 10
Reputation: ippomarley is an unknown quantity at this point 
Solved Threads: 0
ippomarley ippomarley is offline Offline
Newbie Poster

infinite loop with user input

 
0
  #1
Apr 5th, 2009
hi guys, I am having trouble with this code, cause i get an infinite loop. I made nexTxtFile the variable name of the txt file i am creating and writing text to. i want to be able to get user input untill the user does not want to enter anymore text but i don't know how to do that. i used while (scan.hasNext()) but that just loops to infinity. Without the while loop i just get only the first word i type in as user input, how can i fix this? may i please have an example?


File myFile = new File(newTxtFile);
				Writer output = new BufferedWriter(new FileWriter(myFile));
			while (scan.hasNext()) {
                  	
				txt = scan.next ();
				output.write(txt);
				
				
				 }
				output.close();


thanks ippoMarley
Reply With Quote Quick reply to this message  
Join Date: Nov 2008
Posts: 823
Reputation: verruckt24 is a jewel in the rough verruckt24 is a jewel in the rough verruckt24 is a jewel in the rough verruckt24 is a jewel in the rough 
Solved Threads: 73
verruckt24's Avatar
verruckt24 verruckt24 is offline Offline
Practically a Posting Shark

Re: infinite loop with user input

 
0
  #2
Apr 5th, 2009
The hasNext() method blocks waiting for user input, so the scanner always has a token to show up in hasNext and the while loop never actually terminates.

These are the lines from the Scanner docs:
The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.

What you could do is ask the user to input a specific pattern like 'exit' or 'quit' when he's done giving the input and then scan the input looking for this token.
Last edited by verruckt24; Apr 5th, 2009 at 4:08 am.
Get up every morning and take a look at the Forbes' list of richest people. If your name doesn't appear.... GET TO WORK !!!
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:




Views: 795 | Replies: 1
Thread Tools Search this Thread



Tag cloud for Java
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC