无法拆分来自`Scaner`的输入

人气:162 发布:2022-10-16 标签: java split java.util.scanner

问题描述

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。

723