简体   繁体   中英

Java read string with square brackets

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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