[英]Java Scanner - Read line breaks in to a string?
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. 我有一个扫描仪,需要用户输入直到ctrl + d,然后再执行while循环,它将每个单词添加到字符串中,然后打印出来,但是我想知道如何在字符串中也包括\\ n这样的新行指示器哪里有新线。
Scanner sc = new Scanner(System.in);
System.out.println("Enter your string: ");
String x = "";
while (sc.hasNext()){
x+=sc.next() +" ";
}
System.out.println(x);
Eg this code would take the input: 例如,此代码将接受输入:
Hello
Hello
Hello
and print: Hello Hello Hello 并打印: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. 这样我就可以看到每行的结尾
You want to print "\\n" so why don't you print it? 您想打印“ \\ n”,为什么不打印呢?
while (sc.hasNextLine()){
x+=sc.nextLine() +"\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.