Java Reference
In-Depth Information
case, the first half of the
&&
operator fails) or we get a newline. At that point we
return. Note that the line number is updated automatically by
nextChar
. Other-
wise, we have the
/*
case, which is processed starting at line 17.
The
skipComment
routine uses a simplified state machine. The
state
machine
is a common technique used to parse symbols; at any point, it is in
some state, and each input character takes it to a new state. Eventually, it
reaches a state at which a symbol has been recognized.
In
skipComment
, at any point, it has matched 0, 1, or 2 characters of the
*/
terminator, corresponding to states 0, 1, and 2. If it matches two characters, it
can return. Thus, inside the loop, it can be in only state 0 or 1 because, if it is
in state 1 and sees a
/
, it returns immediately. Thus the state can be repre-
sented by a Boolean variable that is
true
if the state machine is in state 1. If it
does not return, it either goes back to state 1 if it encounters a
*
or goes back
to state 0 if it does not. This procedure is stated succinctly at line 23.
If we never find the comment-ending token, eventually
nextChar
returns
false
and the
while
loop terminates, resulting in an error message. The
skipQuote
method, shown in Figure 11.6, is similar. Here, the parameter is the
opening quote character, which is either
"
or
'
. In either case, we need to see
that character as the closing quote. However, we must be prepared to handle
the
\
character; otherwise, our program will report errors when it is run on its
The
state machine
is a common tech-
nique used to parse
symbols; at any
point, it is in some
state, and each
input character
takes it to a new
state. Eventually,
the state machine
reaches a state in
which a symbol has
been recognized.
1
/**
2
* Precondition: We are about to process a quote;
3
* have already seen beginning quote.
4
* Postcondition: Stream will be set immediately after
5
* matching quote
6
*/
7
private void skipQuote( char quoteType )
8
{
9
while( nextChar( ) )
10
{
11
if( ch == quoteType )
12
return;
13
if( ch == '\n' )
14
{
15
errors++;
16
System.out.println( "Missing closed quote at line " +
17
currentLine );
18
return;
19
}
20
else if( ch == '\\' )
21
nextChar( );
22
}
23
}
figure 11.6
The
skipQuote
routine
for moving past an
already started
character or string
constant
Search WWH ::
Custom Search