繁体   English   中英

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

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

我知道默认情况下,扫描程序会跳过空格和换行符。 我的代码有问题,因为我的扫描仪不会忽略“ \\ n”。

例如:输入为“ this is \\ na test”。 期望的输出应该是“这是一个测试”。

这是我到目前为止所做的:

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()忽略指定的定界符(由useDelimiter()可选设置),并读取到当前行的末尾。

由于输入是两行:

this is
a test.

仅返回第一行( this is )。

然后,您将其拆分为空白,因此output将包含[this, is]

由于不再使用扫描仪,因此将永远不会读取第二行( a test. )。

本质上,您的标题是正确的: Java扫描程序不会忽略换行(\\ n)
当您调用nextLine()时,它专门处理了换行符。

您不必使用Scanner来执行此操作

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String result = in.lines().collect(Collectors.joining(" "));

或者,如果您真的想使用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