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);
Eg 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.
You want to print "\\n" so why don't you print it?
while (sc.hasNextLine()){
x+=sc.nextLine() +"\n";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.