Java扫描程序不忽略新行(\n)
我知道默认情况下,扫描器跳过空白和换行。 我的代码有问题,因为扫描仪没有忽略“\n” 例如:输入为“this is\na test”,所需的输出应为“this is a test” 这就是我目前所做的:Java扫描程序不忽略新行(\n),java,hashmap,Java,Hashmap,我知道默认情况下,扫描器跳过空白和换行。 我的代码有问题,因为扫描仪没有忽略“\n” 例如:输入为“this is\na test”,所需的输出应为“this is a test” 这就是我目前所做的: Scanner scan = new Scanner(System.in); String token = scan.nextLine(); String[] output = token.split("\\s+"); for (int i = 0; i < output.length;
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(" ");
}
Scanner scan=新的扫描仪(System.in);
字符串标记=scan.nextLine();
字符串[]输出=token.split(\\s+);
for(int i=0;i
nextLine()
忽略指定的分隔符(由useDelimiter()
设置),并读取到当前行的末尾
由于输入为两行:
这是
测试。
只返回第一行(这是
)
然后将其拆分为空白,这样输出将包含[这是]
由于您不再使用扫描仪,第二行(a test.
)将永远不会被读取
本质上,您的标题是正确的:Java Scanner不会忽略新行(\n)
当您调用nextLine()
时,它专门处理了换行符。您不必使用扫描仪来执行此操作
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String result = in.lines().collect(Collectors.joining(" "));
或者,如果您真的想使用扫描仪
,这也应该可以
Scanner scanner = new Scanner(System.in);
Spliterator<String> si = Spliterators.spliteratorUnknownSize(scanner, Spliterator.ORDERED);
String result = StreamSupport.stream(si, false).collect(Collectors.joining(" "));
Scanner Scanner=新的扫描仪(System.in);
Spliterator si=Spliterators.Spliterator未知(扫描仪,Spliterator.ORDERED);
String result=StreamSupport.stream(si,false).collect(collector.joining)(“”);
Scanner绝对不会忽略空格或换行符。这些空格或换行符用作默认扫描仪的分隔符,尤其是新行是调用Scanner#nextLine()时使用的分隔符
@HovercraftFullOfEels对此解释得很好。您对诸如nextInt
之类的扫描方法感到困惑,它们忽略了新行和空格。nextLine
专门使用新行分隔其返回。我尝试使用scan.usedimiter(“\n”),但没有成功。任何建议都将不胜感激。当然,这将失败。您明确表示应该停止阅读\n
,但这不是您想要的。因此,请定义一个自己的分隔符,列出“#”
,然后编写“这是一个测试。#”