Java Scanner - Read line breaks in to a string?

大兔子大兔子 提交于 2019-12-14 04:01:02

问题


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";
}


来源:https://stackoverflow.com/questions/28754745/java-scanner-read-line-breaks-in-to-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!