Java Reference
In-Depth Information
METHOD
DESCRIPTION
If the argument is
false
, this switches off recognizing comments starting with a double slash.
A
true
argument switches it on again.
slashSlashComments(
boolean flag)
An argument of
true
causes strings to be converted to lowercase before being stored in
sval
.
An argument of
false
switches off lowercase mode.
lowerCaseMode(
boolean flag)
Calling this method causes the next call of the
nextToken()
method to return the
ttype
value
that was set by the previous
nextToken()
call and to leave
sval
and
nval
unchanged.
pushback()
If you want to alter a tokenizer, it is usually better to reset it by calling the
resetSyntax()
method and
then calling the other methods to set up the tokenizer the way that you want. If you adopt this approach,
any special significance attached to particular characters is apparent from your code. The
resetSyntax()
method makes all characters, including whitespace and ordinary characters, so that no character has any spe-
cial significance. In some situations you may need to set a tokenizer up dynamically to suit retrieving each
specific kind of data that you want to extract from the stream. When you want to read the next character as
a character, even if it would otherwise be part of a token, you just need to call
resetSyntax()
before call-
ing
nextToken()
. The character is returned by
nextToken()
and stored in the
ttype
field. To read tokens
subsequently, you have to set the tokenizer up appropriately.
Let's see how you can use this class to read data items from the keyboard.
TRY IT OUT: Creating a Formatted Input Class
One way of reading formatted input is to define your own class that uses a
StreamTokenizer
object to
read from standard input. You can define a class,
FormattedInput
, that defines methods to return vari-
ous types of data items entered via the keyboard:
import java.io.StreamTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class FormattedInput {
// Method to read an int value...
// Method to read a double value...
// Plus methods to read various other data types...
// Helper method to read the next token
private int readToken() {
try {
ttype = tokenizer.nextToken();
return ttype;
} catch (IOException e) { // Error reading in nextToken()
e.printStackTrace();
System.exit(1); // End the program
}
return 0;
}
// Object to tokenize input from the standard input stream
private StreamTokenizer tokenizer = new StreamTokenizer(