1

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)

Mister Smith
  • 27,417
  • 21
  • 110
  • 193
user3712130
  • 87
  • 1
  • 3
  • 8
  • 1
    Please have a look to [this](http://stackoverflow.com/questions/1066318/how-to-read-a-single-char-from-the-console-in-java-as-the-user-types-it) discussion. – Uluaiv Jun 09 '14 at 13:51
  • What you are trying is heavily system dependant : first on what exactly is pasted, then on input buffer management. Could you say on what system you work (Windows, Linux,...). Anyway you should try to log the codes of the characters you read. – Serge Ballesta Jun 09 '14 at 14:54

1 Answers1

1

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.

Mister Smith
  • 27,417
  • 21
  • 110
  • 193
  • Ok, I understand, but I will not be able to add after the last line in each of the console text. Is there any way I can include the last line (even if there is no in the end) ? And is it possible to stop the loop after the user has pasted the text in the console? – user3712130 Jun 09 '14 at 14:36
  • You could grab the text directly from the clipboard. Have a look at [this answer](http://stackoverflow.com/a/7106086). About the second question, the loop only exits when `read` returns -1, and that would happen if the console closed the stream (I'm sorry I don't know about the specific mechanism involved). – Mister Smith Jun 10 '14 at 08:27