无法拆分来自“扫描仪”的输入

问题描述

String command = scanner.next();
String[] split = command.split(" ");
System.out.println(split.length); 

你好,有人知道为什么当我插入"a b c d e f g h i"时会给我长度1吗?

解决方法

next()读取输入直到空格(" "),因此变量command将是"a"而不是"a b c d e f g h i"

您应该使用nextLine()来读取输入内容,包括字母之间的空格:

Scanner scanner = new Scanner(System.in);
String command = scanner.nextLine();
String[] split = command.split(" ");
System.out.println(split.length); 

有关更多信息,请查看doc

,

您只在一行中检索a而不是整行,请使用String命令= Scanner.nextLine();代替。

,

next()nextLine()方法是Scanner用于获取字符串输入的两种不同方法。

next()只能读取输入,直到空格为止。它无法读取两个由空格分隔的单词。另外,next()在读取输入后将光标置于同一行。

nextLine()读取包含单词之间的空格的输入(即,读取直到\ n行的结尾)。读取输入后,nextLine()将光标置于下一行。

因此,这里您应该使用nextLine()而不是next()

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...