Reputation: 15
I want to read the userinput from command line for a specific log entry. My method to read a string:
public static String readString(String message)
{
System.out.print(message);
Scanner scan = new Scanner(System.in);
String response = null;
while (response == null || response.equals("") || response.length() <= 4)
{
if(response != null)
{
System.out.println("Type atleast 5 chars");
System.out.println(message);
}
response = scan.next();
}
return response;
}
So as long as I type only normal literals, everything is working fine. But typing something like:
"[log-123] sample text"
returns into splitting the response.
So why this problem accures and how to avoid it, so all chars till the linebreak will be read proberly.
Upvotes: 0
Views: 674
Reputation: 16129
Scanner.next:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
and
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
So input [log-123] sample text
will be broken at the spaces. It has nothing to do with the brackets.
This may be more what you want:
Scanner.nextLine:
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Upvotes: 3