Hello guys, I'm dealing with stacks and the general concept if pretty straightforward (FILO/LIFO). I'm using a stack to reformat an infix equation to postfix and prefix notation. I've seen several examples of this online, but I'd like to make it my own--so...
I've created a postfix class with the following method:
public void stackPF(String inString) throws PointerOutOfBoundException { inString = inString.trim(); // Statements to evaluate array for (char ch : inString.toCharArray()) { // Evaluate equation in parenthesis System.out.println("Inside Loop"); if (ch == '(') { System.out.println("paran"); operatorStack.push(ch); do { if (ch >= 0 && ch <= 9) { operandStack.push(ch); } else { if (priority(ch) >= operatorStack.peek()) { operatorStack.push(ch); } } } while (ch != ')'); //Pop characters within parenthesis System.out.println("End paran"); operandStack.pop(); operatorStack.pop(); } else { if (ch >= 0 && ch <= 9) { System.out.println("No paran"); operandStack.push(ch); } // Need to account for precedence! else if (ch == '+' || ch == '-' || ch == '/' || ch == '*') { System.out.println("Precedence"); if(operatorStack.stackEmpty()){ operatorStack.push(ch); } else if (priority(ch) >= operatorStack.peek()) { operatorStack.push(ch); operatorStack.pop(); } else { operatorStack.push(ch); } } } size++; } ///Evaluate operators private static int priority(char ch) { switch (ch) { case '(' : return 0; case '-' : case '+': return 1; case '*' : case '/': return 2; } return -1; }
With this, I want to evaluate an equation within the parenthesis, and without parenthesis. In working out the details, I'm unsure whether or not it's necessary to create two separate stacks -- one for the operators and one for the operands. By doing it this way, I can empty the lists depending on parenthesis. The problem is when I enter (10+3)*9, I don't get any results and the program never records any of my values. Any ideas as to what might be causing this?
Within the stack class, I have the following methods (for clarity) in addition to others not here:
public T pop ( ) { if (stackEmpty ( )) { System.out.println ("empty stack"); return null; } else { T popped = (T) head.getData ( ); head = head.getLink ( ); return popped; } } public void displayStack() throws PointerOutOfBoundException { System.out.println("----------------"); while(!empty()) { if(peek() != "(" ){ System.out.print(" " + pop() + " "); } else { break; } System.out.println("\n----------------"); } }
Thanks