/** *
class ParenChecker provides an example of using
* a stack to determine if an EXPR has balanced parenthesis. An
* EXPR is supplied as a command-line argument. The EXPR should
* be specified enclosed in double quotes.
If the EXPR contains an operand with the name P, then the content * of the stack is printed. If the EXPR contains an operand with the * name T, then the top element of the stack is printed.
* * @author G.D.Thurman * @version 99.09.26 */ public class ParenChecker { public static void main(String[] argv) { if (argv.length != 1) { System.err.println("Usage: java ParenChecker \"some EXPR\"\n"); System.exit(1); } Stack stack = new Stack(); for (int n = 0, len = argv[0].length(); n < len; n++) { char c = argv[0].charAt(n); switch (c) { case '(': stack.push(new Character(c)); break; case ')': if (stack.size() == 0) printResult(true /*is bad*/); Character ch = (Character) stack.pop(); break; case 'P': System.out.println(stack); break; case 'T': System.out.println("top() is: " + stack.top()); break; } } printResult(stack.size() != 0); } /** * Print status message and exit the application. */ private static void printResult(boolean isBad) { System.out.println("The parentheses are" + (isBad ? " NOT " : " ") + "correct."); System.exit(isBad ? 1 : 0); } }