Java Reference
In-Depth Information
the current line number is stored in
currentLine
. Finally, an integer that
counts the number of errors is declared at line 53. The constructor,
shown at lines 19 to 21, initializes the error count to 0 and the current
line number to 1 and sets the
PushbackReader
reference.
We can now implement the class methods, which as we mentioned, are
concerned with keeping track of the current line and attempting to differ-
entiate symbols that represent opening and closing tokens from those that
are inside comments, character constants, and string constants. This gen-
eral process of recognizing tokens in a stream of symbols is called
lexical
analysis.
Figure 11.4 shows a pair of routines,
nextChar
and
putBackChar
.
The
nextChar
method reads the next character from
in
, assigns it to
ch
, and
updates
currentLine
if a newline is encountered. It returns
false
only if the
end of the file has been reached. The complementary procedure
putBackChar
Lexical analysis
is
used to ignore
comments and rec-
ognize symbols.
1
/**
2
* nextChar sets ch based on the next character in the input stream.
3
* putBackChar puts the character back onto the stream.
4
* It should be used only once after a call to nextChar.
5
* Both routines adjust currentLine if necessary.
6
*/
7
private boolean nextChar( )
8
{
9
try
10
{
11
int readVal = in.read( );
12
if( readVal == -1 )
13
return false;
14
ch = (char) readVal;
15
if( ch == '\n' )
16
currentLine++;
17
return true;
18
}
19
catch( IOException e )
20
{ return false; }
21
}
22
23
private void putBackChar( )
24
{
25
if( ch == '\n' )
26
currentLine--;
27
try
28
{ in.unread( (int) ch ); }
29
catch( IOException e ) { }
30
}
figure 11.4
The
nextChar
routine for reading the next character, updating
currentLine
if necessary, and returning
true
if not at
the end of file; and the
putBackChar
routine for putting back
ch
and updating
currentLine
if necessary
Search WWH ::
Custom Search