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:)