0

I have this piece of code

private String getMessage(BufferedReader in) throws IOException{

     StringBuilder sb = new StringBuilder();

     while(true){
        char pom = (char) in.read();
        sb.append(pom); 

        if (sb.toString().contains("\r\n")) {                  
               String result = sb.toString();
               result = result.replace("\r\n", "");
               return result;
        }
     }   
} 

I want user to write on console some message. And when he writes '\r\n' console should end its input. But this doesn't work... Don't you have some tips what could be the problem?

And in aditional, i don't want to use in.close(); coz i will need this input later.

1 Answers1

0

Try this:

private String getMessage(BufferedReader in) throws IOException{
    return in.readLine();
}

OK, if you want to do it byte by byte, then you can try this:

private String getMessage(BufferedReader in) throws IOException{
   StringBuilder sb = new StringBuilder();
   char prev = (char) 0;
   char cur = in.read();
   while (prev != '\r' || cur != '\n') {
      sb.append(cur);
      prev = cur;
      cur = in.read();
   }
   return sb.toString();
}
Rudi Angela
  • 1,463
  • 1
  • 12
  • 20