Java Scanner - Read line breaks in to a string?

2019-08-09 03:39发布

问题:

I have a scanner that takes user input until ctrl+d and then a while loop which adds each word to a string and then prints it, but i'd like to know how to also include the new line indicators like \n in the string wherever there is a new line.

Scanner sc = new Scanner(System.in);
System.out.println("Enter your string: ");
String x = "";

while (sc.hasNext()){
  x+=sc.next() +" ";
}
System.out.println(x);

E.g this code would take the input:

Hello
Hello
Hello

and print: Hello Hello Hello

Whereas I would like it to print something like:

Hello\n Hello\n Hello\n

so I can see where each line ends.

回答1:

You want to print "\n" so why don't you print it?

while (sc.hasNextLine()){
  x+=sc.nextLine() +"\n";
}