|
-
September 2nd, 2009, 08:48 AM
#1
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.
-
September 2nd, 2009, 05:29 PM
#2
Re: How to clear BufferedReader w/o creating a new instance..
 Originally Posted by Nim
... 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.
What problem? You just described what the code does - what is the problem?
Is there another way to clear the BufferedReader?
What do you mean by 'clear' ? A Reader reads it's input until there's no more, then it stops.
I don't see why you're create a new Reader every time round your loop. If you could explain what you're trying to do, maybe we could suggest something.
Precise language is not the problem. Clear language is the problem...
R. Feynmann
Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|