Note that there are some explanatory texts on larger screens.

plurals
  1. POPostfix Evaluation using Stacks
    text
    copied!<p>I'm trying to write a method that solves a postfix equation. For ex. </p> <pre><code>1 2 + 3 * </code></pre> <p>This would = <code>9</code></p> <p>As of now I'm getting a <code>ArrayoutofboundsException</code>. I think the problem is around my <code>if(statement)</code> in my <code>postFixEvaluation</code> Method.</p> <p>The first part of code is the method I was talking about where I need the help. After that is the rest of my code. Not sure if yall need to read that or not. </p> <pre><code>public int PostfixEvaluate(String e) { String Operator = ""; int number1; int number2; int result = 0; char c; number1 = 0; number2 = 0; for (int j = 0; j &lt; e.length(); j++) { c = e.charAt(j); if (c == (Integer) (number1)) { s.push(c); } else { number1 = s.pop(); number2 = s.pop(); switch (c) { case '+': result = number1 + number2; break; case '-': result = number1 - number2; break; case '*': result = number1 * number2; break; case '/': result = number1 / number2; break; case '%': result = number1 % number2; break; } } } return result; } public static void main(String[] args) { Stacked st = new Stacked(100); String y = new String("(z * j)/(b * 8) ^2"); String x = new String("10 3 + 9 *"); TestingClass clas = new TestingClass(st); clas.test(y); //System.out.println(stacks.test(y)); clas.PostfixEvaluate(x); } </code></pre> <hr> <p>Here's the rest of code that may be relevant: </p> <pre><code>public class Stacked { int top; char stack[]; int maxLen; public Stacked(int max) { top = 0; maxLen = max; stack = new char[maxLen]; } public void push(int result) { top++; stack[top] = (char) result; } public int pop() { int x; x = stack[top]; //top = top - 1; top--; return x; } public boolean isStackEmpty() { if (top == 0) { System.out.println("Stack is empty " + "Equation Good"); return true; } else System.out.println("Equation is No good"); return false; } public void reset() { top = -1; } public void showStack() { System.out.println(" "); System.out.println("Stack Contents..."); for (int j = top; j &gt; -1; j--) { System.out.println(stack[j]); } System.out.println(" "); } public void showStack0toTop() { System.out.println(" "); System.out.println("Stack Contents..."); for (int j = 0; j &gt;= top; j++) { System.out.println(stack[j]); } System.out.println(" "); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload