简体   繁体   English

Java扫描器不会忽略换行(\\ n)

[英]Java Scanner does not ignore new lines (\n)

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". 我的代码有问题,因为我的扫描仪不会忽略“ \\ n”。

For example: the input is "this is\\na test." 例如:输入为“ 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. nextLine()忽略指定的定界符(由useDelimiter()可选设置),并读取到当前行的末尾。

Since input is two lines: 由于输入是两行:

this is
a test.

only the first line ( this is ) is returned. 仅返回第一行( this is )。

You then split that on whitespace, so output will contain [this, is] . 然后,您将其拆分为空白,因此output将包含[this, is]

Since you never use the scanner again, the second line ( a test. ) will never be read. 由于不再使用扫描仪,因此将永远不会读取第二行( a test. )。

In essence, your title is right on point: Java Scanner does not ignore new lines (\\n) 本质上,您的标题是正确的: Java扫描程序不会忽略换行(\\ n)
It specifically processed the newline when you called nextLine() . 当您调用nextLine()时,它专门处理了换行符。

You don't have to use a Scanner to do this 您不必使用Scanner来执行此操作

        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 scanner = new Scanner(System.in);
        Spliterator<String> si = Spliterators.spliteratorUnknownSize(scanner, Spliterator.ORDERED);
        String result = StreamSupport.stream(si, false).collect(Collectors.joining(" "));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM