Java Reference
In-Depth Information
}
}
The
StreamTokenizer
class in
java.util
provides slightly more capabilities for scanning a
file. It reads characters and assembles them into words, or tokens. It returns these tokens to
you along with a type code describing the kind of token it found. This type code is one of
four predefined types (
StringTokenizer.TT_WORD
,
TT_NUMBER
,
TT_EOF
, or
TT_EOL
for the
end-of-line), or the
char
value of an ordinary character (such as 32 for the space character).
Methods such as
ordinaryCharacter()
allow you to specify how to categorize characters,
while others such as
slashSlashComment()
allow you to enable or disable features.
stack-based calculator:
2 2 + =
4
22 7 / =
3.141592857
I read tokens as they arrive from the
StreamTokenizer
. Numbers are put on the stack. The
four operators (
+
,
-
,
\*
, and
/
) are immediately performed on the two elements at the top of
the stack, and the result is put back on the top of the stack. The
=
operator causes the top ele-
ment to be printed, but is left on the stack so that you can say:
4 5 * = 2 / =
20.0
10.0
Example 10-4. Simple calculator using StreamTokenizer
public
public class
SimpleCalcStreamTok
{
/** The StreamTokenizer Input */
protected
class
SimpleCalcStreamTok
protected
StreamTokenizer tf
;
/** The Output File */
protected
protected
PrintWriter out
=
new
new
PrintWriter
(
System
.
out
,
true
true
);
/** The variable name (not used in this version) */
protected
protected
String variable
;
/** The operand stack */
protected
protected
Stack s
;