Java Reference
In-Depth Information
1
/**
2
* Print an error message for unbalanced symbols.
3
* @return number of errors detected.
4
*/
5
public int checkBalance( )
6
{
7
char ch;
8
Symbol match = null;
9
Stack<Symbol> pendingTokens = new Stack<Symbol>( );
10
11
while( ( ch = tok.getNextOpenClose( ) ) != '\0' )
12
{
13
Symbol lastSymbol = new Symbol( ch, tok.getLineNumber( ) );
14
15
switch( ch )
16
{
17
case '(': case '[': case '{':
18
pendingTokens.push( lastSymbol );
19
break;
20
21
case ')': case ']': case '}':
22
if( pendingTokens.isEmpty( ) )
23
{
24
errors++;
25
System.out.println( "Extraneous " + ch +
26
" at line " + tok.getLineNumber( ) );
27
}
28
else
29
{
30
match = pendingTokens.pop( );
31
checkMatch( match, lastSymbol );
32
}
33
break;
34
35
default: // Cannot happen
36
break;
37
}
38
}
39
40
while( !pendingTokens.isEmpty( ) )
41
{
42
match = pendingTokens.pop( );
43
System.out.println( "Unmatched " + match.token +
44
" at line " + match.theLine );
45
errors++;
46
}
47
return errors + tok.getErrorCount( );
48
}
figure 11.8
The
checkBalance
algorithm
Search WWH ::
Custom Search