问题
I am writing a program to write text to a file based on user input, stopping when a blank line is entered, I.E. when hasNextLine is false. However, after running the program the file contains thousands of instances of the same line of input, which continues to grow until I kill the program. Could someone advise me on where I am going wrong please?
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.PrintWriter;;
public class Lab_Week8_WriteAStory {
public static void main(String[] args) throws FileNotFoundException {
PrintWriter writing = new PrintWriter ("Read and Write Files/output.txt");
Scanner whattotwrite = new Scanner (System.in);
String writetotfile = whattotwrite.nextLine();
do {
writing.println(writetotfile);
}
while (whattotwrite.hasNextLine());
System.out.println ("YOUR TEXT HAS NOW BEEN WRITTEN TO THE FILE.");
whattotwrite.close();
writing.close();
}
}
回答1:
You loop is wrong. Iterator
and Scanner
work like that:
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
...
}
You must always call hasNextLine()
prior to call nextLine()
. The later will advance the internals of scanner (where it is in the file) and the former will tell you if there is remaining line.
The same applies to Iterator
and older Enumeration
.
来源:https://stackoverflow.com/questions/59338401/writing-to-a-file-code-causing-an-endless-loop