Question

I am using java.util.Scanner for things such as nextInt(), and all was working fine as long as I was using a java.lang.Readable (one and only constructor argument). However, when I changed to using an InputStream instead, Scanner.nextInt() never returns. Do you know why?

My implementation of the InputStream looks like this:

private static class ConsoleInputStream extends InputStream {
    ...
    private byte[] buffer;
    private int bufferIndex;
    public int read() throws IOException {
        ...
        while (...) {
            if (buffer != null && bufferIndex < buffer.length) {
                return buffer[bufferIndex++];    // THE COMMENT!
            }
            ...
        }
        ...
    }
}

When I print the data by THE COMMENT I (correctly) get stuff like '1','2','\n' for "12\n", etc. Is there some Scanner hookup, unbeknown to me, that cause this behavior?

Was it helpful?

Solution

From the javadocs for InputStream's read() method:

"Returns: the next byte of data, or -1 if the end of the stream is reached."

I would guess that you're never returning -1?

OTHER TIPS

I think the problem is with your self-built InputStream. Why did you build your own, rather than simply simply using System.in ?

Update:

Wanted input from a JTextField.

OK, got it. It usually doesn't make sense to use I/O handling to read stuff that's already available, in character form, but I can see how that would make your life easier with Scanner.

Still, you could probably have saved yourself some coding and grief by using a "finished" InputStream. What comes to mind is

InputStream is = new ByteArrayInputStream(myTextField.getText().getBytes());

Java I/O is yucky. Be glad the bright people from Sun have encapsulated most of it away for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top