Java Reference
In-Depth Information
If you want to alter a tokenizer, it is usually better to reset it by calling the resetSyntax() method, then
call the other methods to set the tokenizer up the way that you want. If you adopt this approach, any special
significance attached to particular characters will be apparent from your code. The resetSyntax() method
makes all characters, including whitespace, and ordinary characters, so that no character has any special
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, whatever it is, you just need to call resetSyntax() before calling nextToken() . The character
will be returned by nextToken() and stored in the ttype field. To read anything else subsequently, you
have to set the tokenizer up appropriately.
Let's see how we 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 our own class that uses a StreamTokenizer object to
read from standard input. We can define a class, FormattedInput , which will define methods to
return various types of data items entered via the keyboard:
import java.io.*;
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.err);
System.exit(1); // End the program
}
return 0;
}
// Object to tokenize input from the standard input stream
private StreamTokenizer tokenizer = new StreamTokenizer(
new BufferedReader(
new InputStreamReader(System.in)));
private int ttype; // Stores the token type code
}
The default constructor will be quite satisfactory for this class, because the instance variable,
tokenizer , is already initialized. The readToken() method is there for use in the methods that will
read values of various types. It makes the ttype value returned by nextToken() available directly,
and saves having to repeat the try and catch blocks in all the other methods.
Search WWH ::




Custom Search