[英]Cannot split input from `Scanner`
String command = scanner.next();
String[] split = command.split(" ");
System.out.println(split.length);
您好,任何人都知道为什么当我插入"ab c defghi"
时它会返回长度 1 吗?
next()
读取输入直到空格( " "
),因此变量command
将是"a"
而不是"ab c defghi"
您应该使用nextLine()
来读取输入,包括字母之间的空格:
Scanner scanner = new Scanner(System.in);
String command = scanner.nextLine();
String[] split = command.split(" ");
System.out.println(split.length);
有关更多信息,请查看doc 。
您只检索行中的 a 而不是整行 use String command =scanner.nextLine(); 反而。
next()
和nextLine()
方法是 Scanner 用于获取字符串输入的两种不同方法。
next()
只能读取输入直到空格。 它无法读取以空格分隔的两个单词。 此外, next()
在读取输入后将 cursor 放在同一行。
nextLine()
读取输入,包括单词之间的空格(也就是说,它读取到行尾 \n)。 读取输入后, nextLine()
将 cursor 定位在下一行。
所以在这里你应该使用nextLine()
而不是next()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.