简体   繁体   中英

hasNextLine() always returning true within While Loop

This question is linked to a previous question I asked regarding the same program, which can be viewed here:

Writing to a file code causing an endless loop

I have fixed the problem above and rewritten the function as a while loop rather than do while, but now I have the opposite problem that nothing is being written to the file. I've inserting a print statement to tell me the status of hasNextLine, and it is always returning as true even when a blank line has been entered, which is when I want the writer to terminate.

Here is the updated code:

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  {  

        Scanner whatToWrite = new Scanner (System.in);
        PrintWriter writing = new PrintWriter ("Read and Write Files/output.txt");

        while (whatToWrite.hasNextLine()){
            String writeToFile = whatToWrite.nextLine();
            writing.println(writeToFile);
            System.out.println (whatToWrite.hasNextLine());
        }

        writing.close();
        whatToWrite.close();
    }
}

Check the documentation for Scanner.hasNextLine() :

Returns true if there is another line in the input of this scanner. This method may block while waiting for input . The scanner does not advance past any input.

This is what's happening. Since you are using System.in as input source, the method is waiting for your input and once you provide it, it returns true and proceed to the next line and the process repeats itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM