英文:
Cannot split input from `Scanner`
问题
String command = scanner.next();
String[] split = command.split(" ");
System.out.println(split.length);
大家好,有人知道为什么当我输入 "a b c d e f g h i"
时为什么返回给我长度为 1 吗?
英文:
String command = scanner.next();
String[] split = command.split(" ");
System.out.println(split.length);
Hello, anyone knows why it gives me the length 1 back when I insert "a b c d e f g h i"
?
答案1
得分: 0
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);
欲了解更多信息,请查阅文档。
英文:
next()
reads the input till the space (" "
), so the variable command
will be "a"
instead of "a b c d e f g h i"
You should use nextLine()
that reads the input including space between the letters:
Scanner scanner = new Scanner(System.in);
String command = scanner.nextLine();
String[] split = command.split(" ");
System.out.println(split.length);
For more information, take a look at doc.
答案2
得分: 0
你只是检索你的行中的 "a" 而不是整行,请使用 String command = scanner.nextLine(); 来代替。
英文:
You are only retrieving the a in your line and not the full line use String command = scanner.nextLine(); instead.
答案3
得分: 0
next()
和 nextLine()
方法是使用 Scanner 获取字符串输入的两种不同方法。
next()
只能读取输入直到空格为止。它不能读取由空格分隔的两个单词。另外,next()
在读取输入后会将光标定位在同一行。
nextLine()
会读取包括单词之间空格在内的输入(也就是说,它会一直读取到行尾的换行符)。一旦输入被读取,nextLine()
会将光标定位在下一行。
因此在这种情况下,你应该使用 nextLine()
而不是 next()
。
英文:
next()
and nextLine()
methods are two different methods with Scanner for getting String inputs.
next()
can read the input only till the space. It can't read two words separated by space. Also, next()
places the cursor in the same line after reading the input.
nextLine()
reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine()
positions the cursor in the next line.
So here you should use nextLine()
rather than next()
.
专注分享java语言的经验与见解,让所有开发者获益!
评论