I am working on a parenthesis checker program in Java that reads in a text stream from standard input and uses a stack to determine whether or not its parentheses are properly balanced. For example, this should print true for [()]{}{[()()]()}
and false for [(])
. I have made a stack class of my own:
public class Stack {
private char items[];
private int top;
Stack(int n){
items = new char[n];
top = -1;
}
void push(char c){
if(top == items.length-1){
System.out.println("Stack full.");
return;
}
top++;
items[top] = c;
}
char pop(){
if(isEmpty()){
System.out.println("Stack empty");
return (char)0;
}
char p;
p = items[top];
top--;
return p;
}
boolean isEmpty(){
if(top == -1)
return true;
else
return false;
}
}
This is my code for the parenthesis class:
public class Parenthesis {
public static void main(String args[]) throws IOException{
int size;
String str;
Boolean isValid;
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Expression:");
try{
str = br.readLine();
}catch(IOException i)
{
System.out.println("Invalid Input");
str ="";
}
if(checkValid(str))
System.out.println("Valid::All Parentheses are balanced.");
else
System.out.println("Invalid::Parentheses are not balanced.");
}
public static Boolean checkValid(String str){
char sym,prev;
Stack s = new Stack(str.length());
for(int i=0; i<str.length();i++){
sym = str.charAt(i);
if(sym == '(' || sym=='{' || sym=='['){
s.push(sym);
}
if(sym == ')' || sym=='}' || sym==']'){
if(s.isEmpty()){
return false;
}
else{
prev = s.pop();
if(!isPairMatch(prev,sym))
return false;
}
}
}
if(!s.isEmpty())
return false;
return true;
}
public static boolean isPairMatch(char character1, char character2){
if(character1 == '(' && character2 == ')')
return true;
else if(character1 == '{' && character2 == '}')
return true;
else if(character1 == '[' && character2 == ']')
return true;
else
return false;
}
}
Is my way of handling the IOException
right?
I don't think there will a stack overflow ever, as the size of my stack is the string length.. And only if the stack is not empty, then only the checkValid method is going for a s.pop() operation. So should I remove the overflow and underflow check within the stack class, as the are redundent and never occurs??
I'm also curious to know if this is a good way of doing it. Any suggestions are welcome.