简体   繁体   English

来自拆分字符串问题的数组

[英]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(" ");
  • however when i try to print " words[1] " for an input with two or more words it throws a ArrayIndexOutOfBoundsException. 但是,当我尝试为两个或多个单词的输入打印“ words [1]”时,将抛出ArrayIndexOutOfBoundsException。 It would seem that words[1] would simply be the second word in the sentence but the array does not contain it. 看来words [1]只是句子中的第二个单词,但数组不包含它。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM