0

I'm trying to write a method that:

  • Prints out a message (Something like: "Paste your input: ")
  • Waits that the user presses enter.
  • Reads all the lines, that got pasted and adds them up in one String.

(An empty line can be used to determine the end of the input.)

The first syso does the printing part and also the first line gets read correctly, but then it never exits the while loop. Why? There has to be an end?

public static String readInput(String msg) {
    System.out.print(msg);
    String res = "";
    try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
        String line;
        while ((line = buffer.readLine()) != null && !line.isBlank())
            res += "\n" + line;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return res;
}

Ive already seen the following sites, but they all didn't help:

Edit:

The same bug applies for:

public static String readInput(String msg) {
        System.out.print(msg);
        String res = "";
        try (BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in))) {
            res = buffer.lines().reduce("", (r, l) -> r + "\n" + l);
            System.out.println(res);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

Edit 2: I've tried this code in my actual project and in a new test-project, but with different results. Here is a video of that test.

  • 1
    There is no way to know if the user is done copying stuff - I would suggest using a marker for the end. For example the user could copy the lines and then enter "q " for quit or something similar. And in your code you can check if the line matches the marker and exit if it does. – assylias Jan 18 '22 at 15:30

1 Answers1

0

Why wouldn't use this statement?

 while (!(line = buffer.readLine()).isEmpty())

In this case sending empty line will exit the loop.

Although, if you insert large text with empty lines (for example, the beginning of a new paragraph, or a space between them) will terminate the program.

MacCadley
  • 25
  • 1
  • 1
  • 5
  • I've tried that already, but it doesn't work for either isEmpty or isBlank. I honestly have no idea why. –  Jan 18 '22 at 15:32