Pages

Tuesday, November 20, 2012

Stacks-- parenthesis matching

Hi All,

Today our topic of discussion is checking the correctness of parenthesis I mean matching right and left parenthesis using stack.


static Stack<Character> s=new Stack<Character>();
   
   
    public static void main(String[] args) {
        // TODO Auto-generated method stub
       
       
        boolean hasMoreChars=true;
       
        char nextChar='A';
        DataInputStream din=new DataInputStream(System.in);
        while(hasMoreChars){
            try{
                System.out.println("\n Enter a character");
            nextChar=(din.readLine()).charAt(0);
           
            System.out.println(nextChar);
            }
            catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                System.exit(0);
            }
           
            if(nextChar==-1){
                System.out.println("in If\n");
                hasMoreChars=false;
            }
           
            else{
                System.out.println("\n In else");
            if(nextChar=='('||nextChar=='{'||nextChar=='['){
               
                System.out.println("\n In push");
                s.push(nextChar);
            }
            else if(nextChar==')'||nextChar=='}'||nextChar==']'){
               
                System.out.println("\n In pop");
                if(s.isEmpty()){
                    System.out.println("\n there is a mismatch");
                }
               
                else{
                if(nextChar==')'){
                    if(s.pop()=='('){
                        continue;
                       
                    }
                    else{
                        System.out.println("\n there is a mismatch");
                    }
                }
               
                if(nextChar=='}'){
                    if(s.pop()=='{'){
                        continue;
                       
                    }
                    else{
                        System.out.println("\n there is a mismatch");
                    }
                }
               
                if(nextChar==']'){
                    if(s.pop()=='['){
                        continue;
                       
                    }
                    else{
                        System.out.println("\n there is a mismatch");
                    }
                }
               
            }
           
           
        }

    }
   
   
   

}
    }


for the purpose focusing on the problem at hand , not on stack, I have used the stack class in util.  Further more there are some minor mistakes in the above code. It is left for your to find out the mistakes and rectify them as an execercise.






No comments:

Post a Comment