Java扫描仪-读取的行插入字符串了吗? [英] Java Scanner - Read line breaks in to a string?
本文介绍了Java扫描仪-读取的行插入字符串了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个扫描仪,它需要用户输入直到ctrl + d,然后是while循环,它将每个单词添加到字符串中,然后打印出来,但是我想知道如何也包括\ n这样的新行指示符在字符串中只要有新行.
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
并打印: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.
推荐答案
您要打印"\ n",为什么不打印呢?
You want to print "\n" so why don't you print it?
while (sc.hasNextLine()){
x+=sc.nextLine() +"\n";
}
这篇关于Java扫描仪-读取的行插入字符串了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文