class StackObject { char cr; int loc; public StackObject(char c, int l) { cr = c; loc = l; } } class MyStack { Object [] arr; int StackTop; public MyStack() { arr = new Object[20]; StackTop = -1; } public void push (Object o) { StackTop++; arr[StackTop] = o; } public Object pop () { if (StackTop == -1) {return null;} else { StackTop--; return arr[StackTop + 1]; } } } class Auxiliaries { public static boolean matches(char a, char b) { boolean ans = false; if (( a == '(') && (b == ')' )) ans = true; if ((a == '[' ) && (b == ']' )) ans = true; return ans; } } public class ParanthGen { public static void main (String argv []) { char [] str = {'(', '[', ']', '[', ']',')'}; //string to be processed StackObject ObjectOnTop; int i = 0; // to iterate through str boolean notDone = true; //variable to indicate mismatch in the middle of processing str MyStack sta = new MyStack(); while( (i < str.length) && notDone) { if ( (str[i] == '(') || (str[i] == '[')) { sta.push(new StackObject(str[i],i)); } // push onto stack for open paranths else if( (str[i] == ')') || (str[i] == ']') ) { ObjectOnTop = (StackObject) sta.pop(); // pop otherwise, and process as below if (ObjectOnTop == null) { notDone = false; System.out.println("The character " + str[i] + " at position" + i + "has no match"); } else if (! Auxiliaries.matches(ObjectOnTop.cr, str[i]) ) { notDone = false; System.out.println("The " + str[i] + " at position " + i + " does not match the " + ObjectOnTop.cr + " at position " + ObjectOnTop.loc); } } else {System.out.println("invalid character at position" + i); notDone = false; } // Only used if str contains something other than paranths i++; } if ( notDone && (sta.pop() != null) ) System.out.println("Paranths need to be closed"); } }