[英]Array from split String problems
Hello I am using the following java code to split user input into individual words - 您好,我正在使用以下Java代码将用户输入拆分为单个单词-
String command = scanner.next();
command = command.toLowerCase();
String[] words = command.split(" ");
Instead of scanner.next()
, try 尝试使用不是scanner.next()
String command = scanner.nextLine();
This will make sure you read all the words. 这将确保您阅读所有单词。
From the Scanner API : 从扫描仪API中 :
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. 扫描程序使用定界符模式将其输入分为令牌,默认情况下,该模式与空格匹配。
While the javadoc for Scanner#next()
states: 虽然Scanner#next()
的javadoc指出:
Finds and returns the next complete token from this scanner. 查找并返回此扫描仪的下一个完整令牌。 A complete token is preceded and followed by input that matches the delimiter pattern. 完整的标记在其前面,然后是与定界符模式匹配的输入。
So in your case scanner.next()
will return a word with no whitespace , as whitespace is how your scanner likely knows when to stop scanning. 因此,在您的情况下, scanner.next()
将返回不带空格的单词,因为空格是您的扫描器可能知道何时停止扫描的方式。
You might want to use Scanner#nextLine()
or something of the sort instead. 您可能想使用Scanner#nextLine()
或类似的东西。
Try this one, and make sure you have read all input words 试试这个,并确保您已阅读所有输入词
Scanner scanner = Scanner(System.in);
String command = scanner.nextLine();
command = command.toLowerCase();
String[] words = command.split(" ");
Now you can print 现在您可以打印
words[1]
if you have valid index value, 如果您有有效的索引值,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.