CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Threaded View

  1. #1
    Join Date
    Feb 2009
    Posts
    32

    How to clear BufferedReader w/o creating a new instance..

    Run this short program for me:
    Code:
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    public class Test {
      public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          while (true) {
            System.out.print(">");
            char in = (char)br.read();
            if (in == 'x') {
              break;
            }
          }
        }
      }
    }
    Here is a sample of the output:
    Code:
    >the
    >>>>number
    >>>>>>>>of
    >>>>arrows
    ...
    the number of arrows printed after the input is equal to the length of the input plus 2. if you count the line terminator (\n), then it is input.length() + 1. i understand this much: the while loop must be looping through the input 1 character at a time, causing 1 arrow to be printed for each character. the extra arrow is just the last one printed before the stream awaits more input. to confirm that it is looping through the input, type in "example" and see that the program will quit.

    The only solution to this problem is creating a new instance before every read, because even if I enter in 1 character, the new line character is still read.
    Code:
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    public class Test {
      public static void main(String[] args) throws Exception {
          while (true) {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.print(">");
            char in = (char)br.read();
            if (in == 'x') {
              break;
            }
          }
        }
      }
    }
    This is mostly out of curiosity. Is there another way to clear the BufferedReader? I took a look a http://java.sun.com/javase/6/docs/ap...redReader.html but I only found skip. If I use skip, i'd need a way to know the number of characters in the input. Maybe I should just read lines as strings...
    Last edited by Nim; September 2nd, 2009 at 08:50 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured