Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have a PostFix Evaluate program . There is an Error with the evaluation part o

ID: 666102 • Letter: I

Question

I have a PostFix Evaluate program . There is an Error with the evaluation part of the program can u find the error and correct it so that the program evaluate all experssion? Run the code first and see what it is doing wrong. Hint(Empty stack is needed)

Hint : (0.5 is wrong your code should evalute each indivula expression )


import java.io.*;
import java.util.*;

class Express
{
   private Token token;

   Express (Token token) { this.token = token; } // constructor

public int expression ()
   {
String oper;
int result;
result = term ();
while ((token.getName ().equals ("plus")) || (token.getName ().equals ("minus")))
{
   oper = token.getName ();
   token.getToken ();
   if (oper.equals ("plus"))
   {
result = result + term ();
System.out.print ("+ ");
   }
   else
   {
result = result - term ();
System.out.print ("- ");
   }
}
return result;
   }

   public int term ()
   {
String oper;
int result;
result = factor ();
while ((token.getName ().equals ("times")) || (token.getName ().equals ("divide")))
{
   oper = token.getName ();
   token.getToken ();
   if (oper.equals ("times"))
   {
result = result * factor ();
System.out.print ("* ");
   }
   else
   {
result = result / factor ();
System.out.print ("/ ");
   }
}
return result;
   }

   public int factor ()
   {
int result = 0;
if (token.getName ().equals ("digit"))
{
   result = token.getValue ();
   System.out.print ("" + token.getValue () + " ");
   token.getToken ();
}
else
if (token.getName ().equals ("lparen"))
{
   token.getToken ();
   result = expression ();
   if (token.getName ().equals ("rparen"))
token.getToken ();
   else
System.out.print ("Error - missing right parentheses )");
}
else
   System.out.print ("Error - invalid token");
return result;
   }
  
}

public class Post
{
   public static void main (String [] args)
   {
   double a1;
   a1=0.5;

  
System.out.println ("Enter an infix expression:");
Scanner scan = new Scanner(System.in);
  
Token token = new Token ();
token.getToken ();


Express express = new Express (token);
int result = express.expression ();
  
   // String input = scan.nextLine();

  
System.out.println("Evaluated Output is " + a1 + ' ');


   } // main method
}

class Token
{
private int value = 0;
private String name, tokenString;
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
StringTokenizer tokens;

public String getName ()
   {
return name;
}
   public int getValue ()
   {
   return value;
   }


Token ()
{
   try
   {
   tokenString = stdin.readLine ();
tokens = new StringTokenizer (tokenString, "+-*/() ", true);
   } catch
   (IOException e)
   {System.out.println (" Error wrong input");}
} // constructor

   public void getToken ()
   {
  
char ch = ' ';
if (tokens.hasMoreTokens ())
{
   String token = tokens.nextToken ();
   ch = token.charAt (0);
   while (ch == ' ')
   {
token = tokens.nextToken ();
ch = token.charAt (0);
   }
   if (('0' <= ch) && (ch <= '9'))
   {
name = "digit";
try
{ value = Integer.parseInt (token);
} catch (NumberFormatException e) {value = 0;}
   }
else
   { switch (ch)
{
   case '+': name = "plus"; break;
   case '-': name = "minus"; break;
   case '*': name = "times"; break;
   case '/': name = "divide"; break;
   case '(': name = "lparen"; break;
   case ')': name = "rparen"; break;
   default: name = "other";
}
}
}
else name = "other";
   }


}

Explanation / Answer

The approach that you followed seems to be quite complex

1. The issue with you program is it works only for numbers and not characters

2.Your program name and classname should be same

here are the two approaches which is quite direct :

import java.util.Scanner;
import java.util.Stack;


public class PostfixEvaluator {

private static final String OPERATORS = "+-*/";

private Stack<Integer> operandStack;

public int eval(String expression) throws SyntaxError {
  operandStack = new Stack<Integer>();

  
  processTokens(expression);

   return getFinalResult();
}
private int getFinalResult() throws SyntaxError {
  if (operandStack.isEmpty()) {
   throw new SyntaxError ("No value to return!");
  }

  if (operandStack.size() > 1) {
   throw new SyntaxError ("Too many operands!");
  }

  return operandStack.pop();
}


private void processTokens(String expression) throws SyntaxError {
  Scanner tokens = new Scanner(expression);
  String nextToken;
  while (tokens.hasNext()) {
   nextToken = tokens.next();
   
   
   if (Character.isDigit(nextToken.charAt(0))) {
    int value = Integer.parseInt(nextToken);
    operandStack.push(value);
   }
   
   
   else if (isOperator(nextToken)) {
    int result = evalOp(nextToken);
    operandStack.push(result);
   }
   
     else {
    throw new SyntaxError("Invalid character encountered");
   }
  }
  tokens.close();
}


private boolean isOperator(String str) {
   if (str.length() > 1) {
   return false;
  }
   
  return OPERATORS.indexOf(str.charAt(0)) != -1;
}


private int evalOp(String op) throws SyntaxError {
  // Get the operands
  if (operandStack.empty()) {
   throw new SyntaxError("Stack is empty");
  }
  int rhs = operandStack.pop();
  
  if (operandStack.empty()) {
   throw new SyntaxError("Stack is empty");
  }
  int lhs = operandStack.pop();
  
  
  switch (op.charAt(0)) {
  case '+':
   return lhs + rhs;
  case '-':
   return lhs - rhs;
  case '*':
   return lhs * rhs;
  case '/':
   return lhs / rhs;
  }

  // There are no other valid operators.
  assert false;
  return 0;
}


public static void main(String[] args) {
  PostfixEvaluator postfixEvaluator = new PostfixEvaluator();
  System.out.println("Enter expressions to be evaluated");
  Scanner in = new Scanner(System.in);
  String expression = in.nextLine();
  while (!expression.equals("q")) {
   try {
    int result = postfixEvaluator.eval(expression);
    System.out.println("== " + result);
   } catch (SyntaxError ex) {
    System.out.println("Syntax Error: " + ex.getMessage());
   }
   expression = in.nextLine();
  }
}

}

Second approach :


import java.util.StringTokenizer;


public class PostfixEvaluator {
    private static final char ADD = '+', SUBTRACT = '-';
    private static final char MULTIPLY = '*', DIVIDE = '/';

    private ArrayStack stack;

  
    public PostfixEvaluator() {
        stack = new ArrayStack();
    }


    public boolean isValid(String expr) {
      
    }

   
    public int evaluate(String expr) {
        assert (isValid(expr));

        stack = new ArrayStack();
        int op1, op2, result = 0;
        String token;
        StringTokenizer tokenizer = new StringTokenizer(expr);

        while (tokenizer.hasMoreTokens()) {
            token = tokenizer.nextToken();

            if (isOperator(token)) {
                op2 = ((Integer) stack.pop()).intValue();
                op1 = ((Integer) stack.pop()).intValue();
                result = evalSingleOp(token.charAt(0), op1, op2);
                stack.push(new Integer(result));
            }
            else
                stack.push(new Integer(Integer.parseInt(token)));
        }

        result = ((Integer) stack.pop()).intValue();
        return result;
    }


    private boolean isOperator(String token) {
        return (
            token.equals("+")
                || token.equals("-")
                || token.equals("*")
                || token.equals("/"));
    }

   
    private int evalSingleOp(char operation, int op1, int op2) {
        int result = 0;

        switch (operation) {
            case ADD :
                result = op1 + op2;
                break;
            case SUBTRACT :
                result = op1 - op2;
                break;
            case MULTIPLY :
                result = op1 * op2;
                break;
            case DIVIDE :
                result = op1 / op2;
        }

        return result;
    }
}