views:

72

answers:

3

I'm having trouble determining the best way to read some input in for a java program. It needs to read in the individual characters of a roman numeral, and then perform some operation on it.

There are, however, several catches. The input must be read from the standard input, because input redirection is being used.

Additionally, I need to be able to detect both the pair of CR/LF characters to determine an end of line, and the EOF to determine the end of the file.

What's the best way to accomplish this? I've snooped around, and I found out that Scanner doesn't have a .nextChar class (which would have worked perfectly).

A: 

Scanner does not have a nextChar class, because it would be unable to determine what that means. Whitespace are characters; should you skip them or read them?

If the semantics of Scanner are what you want, why not use Scanner to read the entire line (using nextLine), then iterate over the line's characters? If you don't want intraline whitespace, just remove it or ignore it.

jdmichal
A: 

You can use the read method of the FileReader class (which it inherits from the InputStreamReader class). This will read one character at a time and return a -1 when the end of the file/stream is reached.

brainimus
Why a FileReader? Why not just hook an InputStreamReader to System.in since FileReader just inherits its `read()` methods from InputStreamReader and Reader anyway?
Stephen P
@Stephen: Looking at my answer I was initially confused on why I did that as well. After some snooping I found out that the question was edited after I had posted my answer.
brainimus
A: 

Is there something wrong with just System.in.read()? It returns one int (simply cast it to char) and -1 for EOF.

J Hall