class StackObject { String str; int loc; public StackObject(String s, int l) { str = s; loc = l; } } class MyStack { Object [] arr; int StackTop; public MyStack() { arr = new Object [20]; StackTop = -1; } public void push (AnyType o) { StackTop++; arr[StackTop] = o; } public AnyType pop () { if (StackTop == -1) {return null;} else { StackTop--; return (AnyType) (arr[StackTop + 1]); } } } class Auxiliaries { public static boolean matches(String a, String b) { boolean ans = false; if ((a == "(") && (b == ")")) ans = true; if ((a == "[") && (b == "]")) ans = true; return ans; } } public class ParanthGenerics { public static void main (String argv []) { String [] 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 = 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.str, str[i]) ) { notDone = false; System.out.println("The " + str[i] + " at position " + i + " does not match the " + ObjectOnTop.str + " at position " + ObjectOnTop.loc); } } else {System.out.println("invalid character at position" + i);} // Only used if str contains something other than paranths i++; } if (sta.pop() != null) System.out.println("Paranths need to be closed"); } }