简体   繁体   中英

Why cant my while-loop with system.in.read() get the last line in console?

Im stuck with a problem regarding System.in.read(). I want to print everything that is pasted into the console. My code looks like this:

import java.io.IOException;

public class printer {
    public static void main(String[ ] args) { 
        int i;
        try {
            while ((i = System.in.read()) != -1) {
                char c = (char)i;
                System.out.print(c);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. The problem is that if you paste ,for example, three lines into the console the program will then print the two first lines, but not the third. Why is that? It prints the third if i press enter but with a huge space between the second and the third line.

  2. I've also tried to store every char in a string and then print the whole string after the loop, but the loop never ends. Is their a way to stop this specific loop (I will not know how many rows the user will paste)

Your app echoes any line you type (or paste) in the console. Problem is, consoles are a thing of the past, and they were supposed to do stuff line by line. This means your app only prints after having read the new line character, because System.in.read blocks.

The text you are pasting already includes two line breaks, but the last line lacks this delimiter. This is what you are posting, where <nl> means a line break:

    line1<nl>line2<nl>line3

If you go to your fav text editor, paste there, add an additional line break at the end and copy all again with the "select all" menu, you'll see the last line.

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