Note that there are some explanatory texts on larger screens.

plurals
  1. PONeed help in implementing Java Algorithm on Postfix Evaluation
    primarykey
    data
    text
    <p>I've tried writing this code from scratch, coding, and running it but it just doesn't seem to work. This was assigned as lab work in class. The requirements are: Implementing a postfix evaluation with the use of a stack and stack operations (user-defined). I think the algorithm of my program is right, but it always gives me the wrong answer. Here is my code.</p> <pre><code>public class StackApplication { public static class Stack&lt;T&gt; { private int top = 0; private final static int stackMax=100; // highest index of stk array private Object[] stk = new Object[stackMax+1]; //Elements must be cast back. public Stack() { // constructor } public boolean isEmpty(){ if (top==0) return true; else return false; } public void push(T el) { if(top==stackMax) System.out.println("Stack push overflow error"); else top=top+1; stk[top]=el; } public T pop(){ if(isEmpty()){ System.out.println("Stack push underflow error"); return null; } else top=top-1; return(T)stk[top+1]; } public T top(){ if(isEmpty()){ //System.out.println("Stack empty"); return null; } else return (T)stk[top]; } } public static boolean isOperator(char c){ return(c=='+' || c=='-' || c=='/' || c=='*' || c=='^'); } public static double evaluate(double x, char o, double y) { double result=0; switch(o) { case '+' : result=x+y; break; case '-' : result=x-y; break; case '*' : result=x*y; break; case '/' : result=x/y; break; case '^' : result=Math.pow(x, y); break; default : break; } return result; } public static void main(String[] args) { Scanner console=new Scanner(System.in); Stack&lt;Double&gt; s=new Stack&lt;Double&gt;(); System.out.println("Input Postfix form to evaluate:"); String inp=console.nextLine(); char[] chararray=inp.toCharArray(); double b,a; for(int i=0; i&lt;chararray.length; i++) { if(!isOperator(chararray[i])) s.push((double)chararray[i]); else { b=s.pop(); a=s.pop(); double c=evaluate(a, chararray[i], b); s.push(c); } } System.out.println(" " +s.pop()); } } </code></pre> <p>Sample Output: Input Postfix form to evaluate:</p> <pre><code>23+ (Input) 101.0 (Output) 5.0 (Expected output) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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