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

Need help with this part of my java assignment, comments appreciated. This class

ID: 3739877 • Letter: N

Question

Need help with this part of my java assignment, comments appreciated.

This class extends class Expression and represents PrefixExpressions

Interface for class PrefixExpression

public PrefixExpression( String str) : This constructor receives a String containing the expression text. It will invoke the constructor for class Expression, passing in the expression text.

public boolean isLegal(): This method returns true if the first “token” in the tokenList is an operator, AND the last two tokens are operands, AND the number of operands in the expression is equal to the number of operators plus 1.

PrefixExpression

NO ADDITIONAL DATA MEMBERS

+ PrefixExpression( in expr: String): constructor + isLegal(): boolean

+ evaluate(): double

public double evaluate(): This method uses a queue of Strings to evaluate the prefix expression.

o Ensure the expression is legal, if not Stop and throw an exception, using class ArithmeticException

o Enqueue all of the tokens in the tokenList into the queue o if the # of tokens in the queue >= 3,

? Dequeue the 1st 3 values. Into 3 String variables: ie: a, b, & c ? else Stop and throw an exception, using class

ArithmeticException o While not done

? If A is not an operator, and B & C are not operands, then we do not have a subexpression. So;

Enqueue A back onto the queue, and swap values

A =B

B=C

Dequeue a new value into C

Repeat the previous steps until A is an operator and B & C operands

? Once is we have a subexpression

Convert the operands into values of type double

Call the method evaluateSubexpression

Enqueue the result back onto the queue.

o If the number of elements in the queue equals 1, we are “done”.

o Else, dequeued 3 new values into a , b, & c and continue processing.

o When done (one value remaining on the queue) dequeue and return the result of the expression.

Expression Class:

package project2;

import java.util.ArrayList;

public abstract class Expression {

  

   // data member

   protected String expression;

   protected ArrayList<String> tokens;

   // constructor

   public Expression(String expression){

   this.expression = expression;

   tokens = new ArrayList<String>();

   String[] tokenList = expression.split(" "); // convert the string to array of tokens

   // insert the tokens in the list

   for(int i=0;i<tokenList.length;i++)

tokens.add(tokenList[i]);

}

   // method to return the expression

   public String getExpression() {

   return expression;

}

   // method to return the tokens

   public ArrayList<String> getTokens() {

   return tokens;

}

   // method to check if the token is operand or not(i.e can be converted to double or not)

   protected static boolean isOperand(String token) {

   try {

double val = Double.valueOf(token);

return true; // token can be converted to double value

   }catch(NumberFormatException e)

   {

return false; // token cannot be converted to double value

   }

}

   // method to check if the token is operator or not

   protected static boolean isOperator(String token) {

   if(token.equals("+") || token.equals("-")|| token.equals("*") || token.equals("/") || token.equals("%"))

return true;

   return false;

}

   // method to return the value of the token(operand value)

   protected static double getOperandValue(String token) throws NumberFormatException {

   return(Double.valueOf(token));

}

   // method to evaluate the subexpression and return the result

   protected static double evaluateSubExpression(double operand1, String operator, double operand2) {

   double result;

   switch(operator) {

case "+" : result = operand1 + operand2;

   break;

case "-" : result = operand1 - operand2;

   break;

case "*" : result = operand1 * operand2;

   break;

case "/" : result = operand1 / operand2;

   break;

case "%" : result = operand1 % operand2;

   break;

default : result = -1;

   }

return result;

}

   // abstract methods to be implemented in subclass

   public abstract boolean isLegal(); // See my comment on page 3 of instructions.

   public abstract double evaluate();

}

Prefix:

package project2;

public class PrefixExpression extends Expression {

   public PrefixExpression(String expression) {

       // Remember the super constructor

   }

   @Override

   public boolean isLegal() {

       /*

       * See my comment on page 3 of instructions.

       * You can decide to implement isLegal() in Expression class.

       * In which case, you can get rid of this method here.

       */

   }

   @Override

   public double evaluate() {

   }

}

PrefixExpression

NO ADDITIONAL DATA MEMBERS

+ PrefixExpression( in expr: String): constructor + isLegal(): boolean

+ evaluate(): double

Explanation / Answer

Please find my code:

import java.util.ArrayList;

public abstract class Expression {

  

// data member

protected String expression;

protected ArrayList<String> tokens;

// constructor

public Expression(String expression){

this.expression = expression;

tokens = new ArrayList<String>();

String[] tokenList = expression.split(" "); // convert the string to array of tokens

// insert the tokens in the list

for(int i=0;i<tokenList.length;i++)

tokens.add(tokenList[i]);

}

// method to return the expression

public String getExpression() {

return expression;

}

// method to return the tokens

public ArrayList<String> getTokens() {

return tokens;

}

// method to check if the token is operand or not(i.e can be converted to double or not)

protected static boolean isOperand(String token) {

try {

double val = Double.valueOf(token);

return true; // token can be converted to double value

}catch(NumberFormatException e)

{

return false; // token cannot be converted to double value

}

}

// method to check if the token is operator or not

protected static boolean isOperator(String token) {

if(token.equals("+") || token.equals("-")|| token.equals("*") || token.equals("/") || token.equals("%"))

return true;

return false;

}

// method to return the value of the token(operand value)

protected static double getOperandValue(String token) throws NumberFormatException {

return(Double.valueOf(token));

}

// method to evaluate the subexpression and return the result

protected static double evaluateSubExpression(double operand1, String operator, double operand2) {

double result;

switch(operator) {

case "+" : result = operand1 + operand2;

break;

case "-" : result = operand1 - operand2;

break;

case "*" : result = operand1 * operand2;

break;

case "/" : result = operand1 / operand2;

break;

case "%" : result = operand1 % operand2;

break;

default : result = -1;

}

return result;

}

// abstract methods to be implemented in subclass

public abstract boolean isLegal(); // See my comment on page 3 of instructions.

public abstract double evaluate();

}

package project2;

import java.util.Queue;

import java.util.LinkedList;

import java.lang.ArithmeticException;

public class PrefixExpression extends Expression {

public PrefixExpression(String expression) {

// Remember the super constructor

super(expression); // invoking the parent constructor

}

@Override

public boolean isLegal() {

/*

* See my comment on page 3 of instructions.

* You can decide to implement isLegal() in Expression class.

* In which case, you can get rid of this method here.

*/

ArrayList<String> tokenList=getTokens();

int operand_count=0,operator_count=0,count=tokenList.size(),c=0;

  

String t1,t2,t3;

  

for(String obj:tokenList)

{

if(isOperator(obj)) operator_count++;   

else

{

if(isOperand(obj)) operand_count++;

}

c++;

if(c==1) t1=obj;

if(c==count) t3=obj;

if(c==count-1) t2=obj;

}

  

if(count==operand_count+operator_count&&operand_count==operator_count+1&&isOperator(t1)&&isOperand(t2)&&isOperand(t3)) return true; // return true if all conditions satisfy

return false;

}

@Override

public double evaluate() {

double result;

if(!isLegal()) throw new ArithmeticException(expression);

else

{

ArrayList<String> tokenList=getTokens();

Queue<String> q = new LinkedList<>();

for(String obj:tokenList) // enque all tokens into queue

{

q.add(obj);

}

boolean done=false;

String A,B,C;

while(!done)

{

if(q.size()>=3)

{

A=q.remove();B=q.remove();C=q.remove(); // dequeuing first three values of queue

if(isOperator(A)&&isOperand(B)&&isOperand(C))

{

if((A=="/"||A=="%")&&Double.valueOf(C)==0) throw new ArithmeticException(getExpression()); // throw exception if of type 2/0 or 2%0

double val= evaluateSubExpression(Double.valueOf(B),A,Double.valueOf(C)); // evaluate SubExpression

q.add(String.valueOf(val));

}

else

{

q.add(A);

A=B;B=C;

C=q.remove();

}

}

else

{

if(q.size()==1)

{

A=q.remove();

if(isOperand(A)) {done=true;result=Double.valueOf(A);} // final output

else

{

throw new ArithmeticException(getExpression());

}

}

else

{

throw new ArithmeticException(getExpression());

}

}

}

}

return result;

}

public static void main(String args[])

{

PrefixExpression obj=new PrefixExpression("+ 2 * 3 4 ");

System.out.println(obj.evaluate());

}

}

EXPECTED OUTPUT:

INPUT:+2*34

OUTPUT:14