I have a method that's supposed to validate accurate opening and closing parenthesis in a string using java. This method will be used to parse mathematical expressions so it's important for the parenthesis to be balanced. For some reason, it is returning false in both of these runs:
System.out.println(parChecker("(()")); // returns false :-)
System.out.println(parChecker("((()))")); // returns false :-( WHY??
Here is the method that uses a stack to solve the problem. Something is wrong here becuase it's returning false for a balanced set of parenthesis as well. What's the problem? Thank you in advance.
public static boolean parChecker(String str) {
String[] tokens = str.split("");
int size = tokens.length;
Stack theStack = new Stack(size);
int index = 0;
boolean balanced = true;
while ((index < size) && balanced) {
String symbol = tokens[index];
if (symbol.equals("(")) {
theStack.push(symbol);
} else {
if (theStack.isEmpty()) {
balanced = false;
} else {
theStack.pop();
}
}
index++;
}
if (balanced && theStack.isEmpty()) {
return true;
} else {
return false;
}
}
Here is my stack class that I'm using:
public class Stack {
private Object [] stack;
private int maxSize = 0;
private int top;
public Stack(int size){
maxSize = size;
stack = new Object[maxSize];
top = -1;
}
public void push(Object obj){
top++;
stack[top] = obj;
}
public Object pop(){
return stack[top--];
}
public Object peek(){
return stack[top];
}
public boolean isEmpty(){
return (top == -1);
}
public boolean isFull(){
return (top == maxSize -1);
}
}