Wednesday 12 August 2015

Java Program to check whether open parenthesis is closed properly or not


              Java Program to check whether open parenthesis is closed properly or not

Many times we want to do a validation on some formula or some string where we need to check whether open parenthesis is closed properly or not.

for ex:- String strFormula=(1+2);

We are going to implement this using stack where we will push the '(' open parenthesis character as soon as it encounters and we will pop out as soon as we encounters closed parenthesis.


 import java.util.Stack;  
 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class ValidateParenthesis {  
      public static void main(String args[]) {  
           String strFormulaCondition = "(1+2)";  
           boolean result = checkForparenthesis(strFormulaCondition);  
           System.out.println("Result:-" + result);  
           String strNewFormulaCondition = "((1+2)";  
           System.out.println("Result:-"  
                     + checkForparenthesis(strNewFormulaCondition));  
      }  
      /**  
       * It checks whether open parenthesis is closed properly or not in report  
       * formula notation  
       *   
       * @param strReportFormula  
       */  
      public static boolean checkForparenthesis(String strReportFormula) {  
           Stack<Integer> stk = new Stack<Integer>();  
           for (int i = 0; i < strReportFormula.length(); i++) {  
                char ch = strReportFormula.charAt(i);  
                if (ch == '(')  
                     stk.push(i);  
                else if (ch == ')') {  
                     try {  
                          int p = stk.pop() + 1;  
                     } catch (Exception e) {  
                     }  
                }  
           }  
           if (!stk.isEmpty()) {  
                return false;  
           } else {  
                return true;  
           }  
      }  
 }  


Enjoy programming:)



3 comments:

  1. Great help! Thanks!

    ReplyDelete
  2. Not that simple. It's incorrect.
    doesnt work for: "([)]" and the likes.
    what is the use of 'p' here ?

    ReplyDelete
    Replies
    1. Its returning true for the input "([)]". Could you please check again?
      And In this case ,the use of 'p' variable is that you can print what value is popped out from stack,not of much use.

      Thanks

      Delete