I know that by default, the Scanner skips over whitespaces and newlines. There is something wrong with my code because my Scanner does not ignore "\\n".
For example: the input is "this is\\na test." and the desired output should be ""this is a test."
this is what I did so far:
Scanner scan = new Scanner(System.in);
String token = scan.nextLine();
String[] output = token.split("\\s+");
for (int i = 0; i < output.length; i++) {
if (hashmap.containsKey(output[i])) {
output[i] = hashmap.get(output[i]);
}
System.out.print(output[i]);
if (i != output.length - 1) {
System.out.print(" ");
}
nextLine()
ignores the specified delimiter (as optionally set by useDelimiter()
), and reads to the end of the current line.
Since input is two lines:
this is
a test.
only the first line ( this is
) is returned.
You then split that on whitespace, so output
will contain [this, is]
.
Since you never use the scanner again, the second line ( a test.
) will never be read.
In essence, your title is right on point: Java Scanner does not ignore new lines (\\n)
It specifically processed the newline when you called nextLine()
.
You don't have to use a Scanner
to do this
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String result = in.lines().collect(Collectors.joining(" "));
Or if you really want to use a Scanner
this should also work
Scanner scanner = new Scanner(System.in);
Spliterator<String> si = Spliterators.spliteratorUnknownSize(scanner, Spliterator.ORDERED);
String result = StreamSupport.stream(si, false).collect(Collectors.joining(" "));
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.