need help with this part of my java assignment. Comments appreciated. This class
ID: 3739879 • Letter: N
Question
need help with this part of my java assignment. Comments appreciated.
This class extends class Expression and represents PostfixExpressions
Interface for class PostfixExpression
public PostfixExpression( 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 last “token” in the tokenList is an operator, AND the first two tokens are operands, AND the number of operands in the expression is equal to the number of operators plus 1.
PostfixExpression
NO ADDITIONAL DATA MEMBERS
+ PostfixExpression( in expr: String): constructor + isLegal(): boolean
+ evaluate(): double
public double evaluate(): This method uses a stack of type Double to evaluate the postfix expression.
o Ensure the expression is legal, if not Stop and throw an exception, using class ArithmeticException
o Obtain the tokenList
o if the # of tokens in the tokenList < 3, Stop and throw an exception,
using class ArithmeticException
o Iterate through the token list
? if the current token is an operand, convert it to type double and
push onto the stack.
? if the current token is an operator:
• if the size of the stack is >=2,
o pop a value from the stack into “operand2”, and
pop a second value from the stack into “operand1” o Evaluate the subexpression.. calling
evaluateSubExpression
o push the result back onto the stack
• else
o Stop and throw an exception, using class
ArithmeticException
o When done (you are at the end of the token list):
o if ONE value remains on the stack, pop and return the value
o else Stop and throw an exception, using class ArithmeticException
My 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();
}
Given postfix code:
package project2;
public class PostfixExpression extends Expression {
// Feel free to create other private/protected members, methods, or constructors.
public PostfixExpression(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() {
}
}
Test class:
package project2;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.AfterClass;
import org.junit.Test;
public class ExpressionTest {
private static final double DELTA = 0.00000000001;
private static final double LEGAL_DRINKING_AGE = 21;
private static int score = 0;
@AfterClass
public static void printScore() {
System.out.println(score + "/90 + ?/10 Documentation");
}
// Testing Getters
@Test
public void testGetPrefixExpression() {
assertEquals("", new PrefixExpression("").getExpression());
assertEquals(" ", new PrefixExpression(" ").getExpression());
assertEquals("+", new PrefixExpression("+").getExpression());
assertEquals("1", new PrefixExpression("1").getExpression());
assertEquals("+ 1.0 .1", new PrefixExpression("+ 1.0 .1").getExpression());
assertEquals("- 0.5 -.1", new PrefixExpression("- 0.5 -.1").getExpression());
assertEquals("0.5 -.1 /", new PrefixExpression("0.5 -.1 /").getExpression());
assertEquals("0.5 -.1 * % abc", new PrefixExpression("0.5 -.1 * % abc").getExpression());
assertEquals("", new PostfixExpression("").getExpression());
assertEquals(" ", new PostfixExpression(" ").getExpression());
assertEquals("+", new PostfixExpression("+").getExpression());
assertEquals("1", new PostfixExpression("1").getExpression());
assertEquals("+ 1.0 .1", new PostfixExpression("+ 1.0 .1").getExpression());
assertEquals("- 0.5 -.1", new PostfixExpression("- 0.5 -.1").getExpression());
assertEquals("0.5 -.1 /", new PostfixExpression("0.5 -.1 /").getExpression());
assertEquals("0.5 -.1 * % abc", new PostfixExpression("0.5 -.1 * % abc").getExpression());
score += 5;
}
@Test
public void testGetTokens() {
assertEquals(Arrays.asList("+"), new PrefixExpression("+").getTokens());
assertEquals(Arrays.asList("1"), new PrefixExpression("1").getTokens());
assertEquals(Arrays.asList("+", "1.0", "0.1"),
new PrefixExpression("+ 1.0 0.1").getTokens());
assertEquals(Arrays.asList("-", "0.5", "-0.1"),
new PrefixExpression("- 0.5 -0.1").getTokens());
assertEquals(Arrays.asList("0.5", "-0.1", "*", "%", "abc"),
new PrefixExpression("0.5 -0.1 * % abc").getTokens());
assertEquals(Arrays.asList("+"), new PostfixExpression("+").getTokens());
assertEquals(Arrays.asList("1"), new PostfixExpression("1").getTokens());
assertEquals(Arrays.asList("+", "1.0", "0.1"),
new PostfixExpression("+ 1.0 0.1").getTokens());
assertEquals(Arrays.asList("-", "0.5", "-0.1"),
new PostfixExpression("- 0.5 -0.1").getTokens());
assertEquals(Arrays.asList("0.5", "-0.1", "*", "%", "abc"),
new PostfixExpression("0.5 -0.1 * % abc").getTokens());
score += 10;
}
@Test
public void testIsLegalPrefixExpression() {
assertFalse(new PrefixExpression("").isLegal());
assertFalse(new PrefixExpression(" ").isLegal());
assertFalse(new PrefixExpression("-").isLegal());
assertFalse(new PrefixExpression("1 1 -").isLegal());
assertFalse(new PrefixExpression("+ 1- 1").isLegal());
assertFalse(new PrefixExpression("1 / 2").isLegal());
assertFalse(new PrefixExpression("+ 1 2 3 -").isLegal());
assertFalse(new PrefixExpression("* / 5. -2 1 - 2").isLegal());
assertTrue(new PrefixExpression("+ 1 2").isLegal());
assertTrue(new PrefixExpression("+ 1 - 2 3").isLegal());
assertTrue(new PrefixExpression("/ 2 1.5").isLegal());
assertTrue(new PrefixExpression("% .3 -47.99").isLegal());
assertTrue(new PrefixExpression("+ 1 2 3 4 + + 5 + + + 6 7").isLegal());
score += 10;
}
@Test
public void testIsLegalPostfixExpression() {
assertFalse(new PostfixExpression("").isLegal());
assertFalse(new PostfixExpression(" ").isLegal());
assertFalse(new PostfixExpression("-").isLegal());
assertFalse(new PostfixExpression("- 1 1").isLegal());
assertFalse(new PostfixExpression("1 1- +").isLegal());
assertFalse(new PostfixExpression("1 / 2").isLegal());
assertFalse(new PostfixExpression("+ 1 2 3 -").isLegal());
assertFalse(new PostfixExpression("5. -2 1 - 2 % * / ").isLegal());
assertTrue(new PostfixExpression("1 2 +").isLegal());
assertTrue(new PostfixExpression("1 2 + 3 -").isLegal());
assertTrue(new PostfixExpression("2 1.5 / ").isLegal());
assertTrue(new PostfixExpression(".3 -47.99 %").isLegal());
assertTrue(new PostfixExpression("1 2 3 4 + + 5 + + + 6 7 +").isLegal());
score += 10;
}
@Test
public void evalSubExpression() {
assertEquals(1.0, Expression.evaluateSubExpression(-1, "+", 2), DELTA);
assertEquals(-1.0, Expression.evaluateSubExpression(1, "-", 2), DELTA);
assertEquals(0.0, Expression.evaluateSubExpression(1, "*", 0), DELTA);
assertEquals(0.5, Expression.evaluateSubExpression(-1, "/", -2), DELTA);
assertEquals(0.0, Expression.evaluateSubExpression(4, "%", 2), DELTA);
score += 15;
}
@Test
public void evalPrefixExpression() {
assertEquals(LEGAL_DRINKING_AGE, new PrefixExpression("* - 9 2 3").evaluate(), DELTA);
assertEquals(10.5, new PrefixExpression("/ * + 5 2 3 2").evaluate(), DELTA);
assertEquals(0.5, new PrefixExpression("% / * + 5 2 3 2 2").evaluate(), DELTA);
assertEquals(0.5, new PrefixExpression("/ * - 9 11 -.5 2").evaluate(), DELTA);
score += 20;
}
@Test
public void evalPostfixExpression() {
assertEquals(LEGAL_DRINKING_AGE, new PostfixExpression("3 9 2 - *").evaluate(), DELTA);
assertEquals(10.5, new PostfixExpression("3 5 2 + * 2 /").evaluate(), DELTA);
assertEquals(0.5, new PostfixExpression("3 5 2 + * 2 / 2 %").evaluate(), DELTA);
assertEquals(0.5, new PostfixExpression("-.5 9 11 - * 2 /").evaluate(), DELTA);
score += 20;
}
}
PostfixExpression
NO ADDITIONAL DATA MEMBERS
+ PostfixExpression( in expr: String): constructor + isLegal(): boolean
+ evaluate(): double
Explanation / Answer
package project2;
import java.util.ArrayList;
import java.util.Stack;
public class PostfixExpression extends Expression{
public PostfixExpression(String expression) {
super(expression);
}
//method that returns if it’s a legal postfix expression or not
@Override
public boolean isLegal() {
// obtain a token list
ArrayList<String> tokenList = getTokens();
// check if # of tokens < 3 then its illegal
if(tokenList.size() < 3)
return false;
// check if first two tokens are operands or not
if((!isOperand(tokenList.get(0))) || (!(isOperand(tokenList.get(1)))))
return false;
// check if last token is operator or not
if(!isOperator(tokenList.get(tokenList.size()-1)))
return false;
int operators=0;
int operands =0;
// loop to count the # of operators and operands in the expression
for(int i=0;i<tokenList.size();i++)
{
if(isOperand(tokenList.get(i)))
operands++;
else if(isOperator(tokenList.get(i)))
operators++;
}
// check if # of operands = # of operators + 1
if(operands != (operators +1))
return false;
return true;
}
// method to evaluate and return the result of the postfix expression
@Override
public double evaluate() {
// check if expression is legal or not
if(!isLegal())
{
throw new ArithmeticException();
}
// obtain a token list
ArrayList<String> tokenList = getTokens();
// check if # of tokens < 3
if(tokenList.size()<3)
throw new ArithmeticException();
Stack<Double> stack = new Stack<Double>();
// loop to calculate the result of the expression
for(int i=0;i<tokenList.size();i++)
{
if(isOperand(tokenList.get(i)))
stack.push(getOperandValue(tokenList.get(i)));
else if(isOperator(tokenList.get(i)))
{
if(stack.size()>=2)
{
double operand2 = stack.pop();
double operand1 = stack.pop();
double result = evaluateSubExpression(operand1,tokenList.get(i),operand2);
stack.push(result);
}else
throw new ArithmeticException();
}
}
if(stack.size()==1)
return stack.pop();
else
throw new ArithmeticException();
}
}
// end of PostfixExpression
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.