Parse an arithmetic expression for matched parentheses...much better than the book!!
public class useStack {
public static void main(String[] argv)
{
String expression;
int errorPlace;
expression="{[a+b]/3} +(56-109)";
errorPlace=matchParen(expression);
System.out.println("Error code "+errorPlace);
}
// Parse the arithmetic expression
// return position of error
// return -1 if line is OK
public static int matchParen(String exp)
{
Stack myStack=new Stack(20);
int i,j,k;
char input;
for(i=0;i<exp.length();i++)
{
input=exp.charAt(i);
switch(input)
{
case '{': myStack.push('}');
break;
case '[': myStack.push(']');
break;
case '(': myStack.push(')');
break;
case ')':
case '}':
case ']':
if (myStack.isEmpty()) return(i); // error!
if(input!=myStack.pop())
return(i); //error!!
break;
// made it to here ? No
error!!!!
default :
}
}
return(myStack.isEmpty()? -1 : i); // if stack is empty then no error, otherwise error
}
}