0

Hello I am using the following java code to split user input into individual words -

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. It would seem that words[1] would simply be the second word in the sentence but the array does not contain it.
1
  • its just because of may be it wont have that size. dont u think that? might be Commented May 16, 2014 at 6:08

3 Answers 3

3

Instead of scanner.next(), try

String command = scanner.nextLine();

This will make sure you read all the words.

Sign up to request clarification or add additional context in comments.

Comments

2

From the Scanner API:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

While the javadoc for Scanner#next() states:

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.

You might want to use Scanner#nextLine() or something of the sort instead.

Comments

0

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,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.