Writing to a file code causing an endless loop

走远了吗. 提交于 2020-01-25 07:54:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!