HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Parenthesis checker

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
checkerparenthesisstackoverflow

Problem

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=='}' ||

Solution

A little code reduce in two functions:

char pop(){
    if(isEmpty()){
        System.out.println("Stack empty");
        return (char)0;
    }
    return items[top--];
}

boolean isEmpty(){
    return top == -1;
}

Code Snippets

char pop(){
    if(isEmpty()){
        System.out.println("Stack empty");
        return (char)0;
    }
    return items[top--];
}

boolean isEmpty(){
    return top == -1;
}

Context

StackExchange Code Review Q#68834, answer score: 2

Revisions (0)

No revisions yet.