Scanner类为什么要返回 作为 IntelliJ+Windows 上的第一个换行符?

问题描述 投票:0回答:1

当我在 Windows 10 上从 IntelliJ 运行以下类时:

import java.util.Scanner;
public class Main
{
    public static void main(String ... args)
    {
        Scanner reader = new Scanner(System.in);
        reader.useDelimiter("");
        String s = reader.next();
        System.out.println((int)s.charAt(0));
    }
}

然后我按

Enter
键作为输入,输出是:

10

这让我感到困惑,因为 Windows 行分隔符是 2 个字符序列

\r\n
。为什么没有输出

13

?

java windows intellij-idea input newline
1个回答
0
投票

当我们稍微更改您的代码时,读取像

"\r\n"
这样的预定义数据而不是像
System.in
这样的数据

import java.util.Scanner;
public class Main
{
    public static void main(String ... args)
    {
        Scanner reader = new Scanner("\r\n");
        reader.useDelimiter("");

        String s = reader.next();
        System.out.println((int)s.charAt(0));

        String s2 = reader.next();
        System.out.println((int)s2.charAt(0));
    }
}

然后结果我们会看到

13
10

对应于 Unicode 表中的

\r
\n
的索引,正如预期的那样。

这表明您用来运行此代码的工具设置为仅使用

\n
作为行分隔符,而不是 Windows 中使用的
\r\n

© www.soinside.com 2019 - 2024. All rights reserved.