Reputation: 1
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(" ");
Upvotes: 0
Views: 51
Reputation: 626
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,
Upvotes: 0
Reputation: 11867
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.
Upvotes: 2
Reputation: 7501
Instead of scanner.next()
, try
String command = scanner.nextLine();
This will make sure you read all the words.
Upvotes: 3