Java Balanced Expressions Check | Code Factory

Reference Link : Link

Donate : Link

Write a program to examine whether the pairs and the orders of “{“,”}”,”[“,”]”,”(“,”)” are correct in exp.

public class CheckStringPattern {
static int i = 0;
static char openC = '{', closeC = '}', openR = '[', closeR = ']', openB = '(', closeB = ')';

public static void main(String args[]) {
System.out.println("CheckStringPattern.main()");
String str = "({}()[[]][[[]]]({({{}()})}))";
char array[] = new char[str.length()];

char ch[] = str.toCharArray();
for(char c : ch) {
if(c == openC || c == openR || c == openB) {
array[i] = c;
i = i + 1;
}
if((c == closeC || c == closeR || c == closeB)) {
if(isCloseExist(c, array)) {
i = i - 1;
} else {
i = 1; //set any value in i (other than 0) so it not correct in first IF
break;
}
}
}
if(i == 0) {
System.out.println("Right");
} else {
System.err.println("Wrong");
}
}

private static boolean isCloseExist(char c, char[] array) {
if(i > 0) {
System.out.println(array[i-1] + " : " + c);
if(closeC == c) {
if(array[i-1] != openC) {
return false;
}
} else if(closeR == c) {
if(array[i-1] != openR) {
return false;
}
} else if(closeB == c) {
if(array[i-1] != openB) {
return false;
}
}
return true;
}
return false;
}
}