Java Reference
In-Depth Information
switch (nextCharacter)
{
case '(': case '[': case '{':
openDelimiterStack.push(nextCharacter);
break ;
case ')': case ']': case '}':
if (openDelimiterStack.isEmpty())
isBalanced = false ;
else
{
char openDelimiter = openDelimiterStack.pop();
isBalanced = isPaired(openDelimiter, nextCharacter);
} // end if
break ;
default : break ;
} // end switch
} // end for
if (!openDelimiterStack.isEmpty())
isBalanced = false ;
return isBalanced;
} // end checkBalance
// Returns true if the given characters, open and close, form a pair
// of parentheses, brackets, or braces.
private static boolean isPaired( char open, char close)
{
return (open == '(' && close == ')') ||
(open == '[' && close == ']') ||
(open == '{' && close == '}');
} // end isPaired
} // end BalanceChecker
The following statements provide an example of how you might use this class:
String expression = "a {b [c (d + e)/2 - f] + 1}";
boolean isBalanced = BalanceChecker.checkBalance(expression);
if (isBalanced)
System.out.println(expression + " is balanced");
else
System.out.println(expression + " is not balanced");
A Problem Solved: Transforming an Infix Expression to a Postfix Expression
Our ultimate goal is to show you how to evaluate infix algebraic expressions, but postfix expres-
sions are easier to evaluate. So we first look at how to represent an infix expression by using
postfix notation.
 
 
Search WWH ::




Custom Search