Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Reading a String with Scanner and ignoring whitespace

800306Jul 20 2007 — edited Jul 20 2007
Hi,

This has probably been asked a million times, and I've searched Google and these forums, but I haven't found an answer that works for me.

I have some class that needs to read user input from the command line, so I figured I'd use Scanner, since I've seen it used umpteen-hundred times in all the "do my homework" threads. I want to print out some line to the terminal, which will prompt the user to enter something. The user should then enter something and hit enter, and the Scanner should store the input in a variable of sorts.

I've tried using Scanner.nextLine(), but that does not block for user input and the program terminates. I've tried Scanner.next() which does block for user input and allows the user to input something, but I cannot find a way to read the entire String; it will stop reading when it reaches whitespace. I've tried using a delimiter, but that seems to terminate the program when I prompt for the input, similar to Scanner.nextLine().

Here's what I have at the moment:
Scanner scanner = new Scanner(System.in); //I have also tried useDelimiter("\\s")
System.out.print("Enter the desired command: ");
String name = scanner.next();
System.out.println("Command entered: " + name);
The above code will work if the command is only one word, e.g. "connect". If the command is more than one word, it will only store the first word in the name variable. Again, I've tried using a delimiter for whitespace, but that hasn't worked.

Is there a way to solve this problem? Perhaps I need to use another tool to read user input from the terminal? Am I just missing something? Do I need to explain more?

Any advice is appreciated.

Thanks
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 17 2007
Added on Jul 20 2007
2 comments
1,832 views