【问题标题】:Cannot split input from `Scanner`无法从“扫描仪”拆分输入
【发布时间】:2020-08-14 09:58:45
【问题描述】:
String command = scanner.next();
String[] split = command.split(" ");
System.out.println(split.length);
你好,有人知道为什么当我插入 "a b c d e f g h i" 时它会返回长度 1 吗?
【问题讨论】:
标签:
java
split
java.util.scanner
【解决方案1】:
您只检索行中的 a 而不是整行使用 String command =scanner.nextLine();而是。
【解决方案2】:
next() 和 nextLine() 方法是使用 Scanner 获取字符串输入的两种不同方法。
next() 只能读取输入直到空格。它无法读取以空格分隔的两个单词。此外,next() 在读取输入后会将光标置于同一行。
nextLine() 读取输入,包括单词之间的空格(也就是说,它读取到行尾 \n)。读取输入后,nextLine() 将光标定位到下一行。
所以在这里你应该使用nextLine() 而不是next()。
【解决方案3】:
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。