Reader returns '?' instead of EOF

D

David Kensche

Hi,
I'm reading a String from a reader. When the string
is done the ready() method remains true and question
marks are read. So this snippet does not terminate:

reader = new PushbackReader(new StringReader(expression));
parsed = "";
StringExpression expr = new StringExpression(symbolTable);
char current;
while(reader.ready()) {
do {
current = (char)reader.read();
} while(current == ' ');
parsed += current;
if(current == '\'') {
expr.appendConstant(parseConstant());
} else if(current == '?') {
expr.appendVariable(parseVariableName());
}
}

Can anybody help?

Thanks beforehand,
David
 
C

Chris Smith

David said:
I'm reading a String from a reader. When the string
is done the ready() method remains true and question
marks are read.

David,

The ready() method doesn't do what you think it does. All the ready()
method does is check whether you can read from the Reader without
blocking. Since a StringReader will never block, ready() will most
likely always return true. Note that there's nothing in the
documentation for ready() that would indicate that it should return
false when you reach the end of stream. I don't know where you got that
expectation from.

The right way to detect end of stream is to watch for the return value
of the read() method to be -1.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
G

Gordon Beaton

I'm reading a String from a reader. When the string is done the
ready() method remains true and question marks are read. So this
snippet does not terminate:

That's the problem with using ready(). It hides EOF from you.

But there's no need to call ready() at all in your example. You can
simply call read() until it indicates that EOF has been reached:

int c;

while ((c = reader.read()) != -1) {
current = (char)c;
if (current == ' ') continue;

[ ... remaining lines... ]
}

/gordon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top