作用:检查括号的开关是否正确,如果有错误,返回错误的第几行和总共有几处错误
package com.tokenizer.cc; import java.io.Reader; import java.util.Stack; /** * Balance class: check for balanced symbols * @author SunnyBoy * @version Time:2017年8月5日 上午10:39:08 */ public class Balance { private Tokenizer tok; private int errors; public Balance(Reader inStream) { errors = 0; tok = new Tokenizer(inStream); } /** * Print an error message for unbalanced symbols. * @return number of errors detected. */ public int checkBalance() { char ch; Symbol match = null; Stack<Symbol> pendingTokens = new Stack<Symbol>(); while ((ch = tok.getNextOpenClose()) != '\0') { Symbol lastSymbol = new Symbol(ch, tok.getLineNumber()); switch (ch) { case '(': case '[': case '{': pendingTokens.push(lastSymbol); break; case ')': case ']': case '}': if (pendingTokens.isEmpty()) { errors++; System.out.println("Extraneous " + ch + " at line " + tok.getLineNumber()); ; } else { match = pendingTokens.pop(); checkMath(match, lastSymbol); } break; default: break; } } while (!pendingTokens.isEmpty()) { match = pendingTokens.pop(); System.out.println("Unmatched " + match.token + " at line " + match.theLine); errors++; } return errors + tok.getErrorCount(); } /** * Print an error message if clSym does not match opSym. * Update errors. * @param opSym * @param clSym */ private void checkMath(Symbol opSym, Symbol clSym) { if (opSym.token == '(' && clSym.token != ')' || opSym.token == '[' && clSym.token != ']' || opSym.token == '{' && clSym.token != '}') { System.out.println("Found " + clSym.token + " on line " + tok.getLineNumber() + "; does not match " + opSym.token + " at line " + opSym.theLine); errors++; } } /** * Symbol nested class; * represents what will be placed on the stack. */ private static class Symbol { public char token; public int theLine; public Symbol(char tok, int line) { token = tok; theLine = line; } } }