- #1
- 2,076
- 140
Homework Statement
I'm trying to create a program which evaluates boolean expressions consisting of ()[]{}XYZ'!| 01TF. Right now I'm working on a bracket matching algorithm that will determine if the brackets match in a given expression.
The problem I'm getting is it's telling me I'm not throwing the proper exceptions for some reason even though I'm pretty sure I am inside my matching brackets code.
Here's my code which concerns this from my StackADT<T> class which I manually wrote. I used an ArrayList as my store. Just the bracket code, constructors, top, pop and push methods are below :
Constructors :
Code:
//Used to create a BOUNDED capacity stack
public StackADT(int capacity){
isBoundedCapacity = true;
boundedCapacity = Math.abs(capacity);
Operators = new ArrayList<T>(boundedCapacity);
}
//Used to create an UNBOUNDED capacity stack
public StackADT(){
isBoundedCapacity = false;
boundedCapacity = StackProtocol.INITIAL_CAPACITY;
Operators = new ArrayList<T>(boundedCapacity);
}
Top, pop and push :
Code:
@Override
public T top() throws StackUnderflowException{
if(isEmpty())
throw new StackUnderflowException();
return Operators.get(topOfStack);
}
@Override
public T pop() throws StackUnderflowException {
if(isEmpty())
throw new StackUnderflowException();
return Operators.remove(topOfStack--);
}
@Override
public void push(T item) throws BoundedCapacityOverFlowException {
if(size() == boundedCapacity) {
if(isBoundedCapacity())
throw new BoundedCapacityOverFlowException();
else {
boundedCapacity *= 2;
Operators.ensureCapacity(boundedCapacity); //Automatically increases the stack bound
}
}
topOfStack++;
Operators.add(item);
}
Matching brackets code ( Located in another class ):
Code:
public void validateMatchingBrackets() throws MissmatchedBracketsException {
StackADT<Character> operationStack = new StackADT<Character>(); //Empty unbounded stack
for(int i=0; i<booleanExpression.length(); i++) { //Loop over the expression
Character c = booleanExpression.charAt(i);
if((c == '(' || c == '{' || c == '[')) //If c is an open bracket
operationStack.push(c); //Push it onto the stack
else if(c == ')' || c == '}' || c == ']') { //Else if c is a close bracket
if(operationStack.isEmpty()) //First check if the stack is empty which means we have no match
throw new MissmatchedBracketsException(); //Throw the exception
if( (c == ')' && operationStack.top() == '(') //If the stack wasn't empty, find the match and pop
|| (c == ']' && operationStack.top() == '[')
|| (c == '}' && operationStack.top() == '{') )
operationStack.pop();
}
}
if(!operationStack.isEmpty()) //After the loop, if the stack is not empty, then throw an exception
throw new MissmatchedBracketsException();
}
If anyone could help me pinpoint what's wrong with my bracket code it would be very helpful :).