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:)

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.

This article has been dead for over six months. Start a new discussion instead.