Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

JAVA: debug/modify these implementations of prefixExpression class, postfixExpression class, and expression to pass expressionTest interface: public class PrefixExpression extends Expression { // Feel free to

JAVA: debug/modify these implementations of prefixExpression class, postfixExpression class, and expression to pass expressionTest

interface:

public class PrefixExpression extends Expression {

// Feel free to create other private/protected members, methods, or constructors.

public PostfixExpression(String expression) {

// Remember the super constructor // This constructor receives a String containing the expression text. It will invoke the constructor for class Expression, passing in the expression text.

super(expression);

}

@Override

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.

String firstToken = super.tokens.get(0);

String lastButOneToken = tokens.get(tokens.size() - 2);

String lastToken = tokens.get(tokens.size() - 1);

int operatorCount = 0;

int operandCount = 0;

if(isOperator(firstToken) && isOperand(lastButOneToken) && isOperand(lastToken)){ //the first token in the tokenList is an operator,

for(String token : tokens){

if(isOperator(token)){

operatorCount++;

}

if(isOperand(token)){

operandCount++;

}

}

return operandCount == operatorCount + 1; //the number of operands in the expression is equal to the number of operators plus 1.

}else {

return false;

}

}

@Override

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.*/

String a, b, c;

Queue myQueue = new LinkedBlockingQueue();

double result = 0.0;

if (!isLegal()) {

throw new ArithmeticException();

}

else {

for (int i = 0; i < super.tokens.size(); i++) {

myQueue.offer(super.getTokens().get(i));

}

if (myQueue.size() >= 3) {

a = myQueue.poll();

b = myQueue.poll();

c = myQueue.poll();

}

else

throw new ArithmeticException();

while (myQueue.size() != 1) {

if (!super.isOperator(a) || !super.isOperand(b) || !super.isOperand(c)) {

myQueue.offer(a);

a = b;

b = c;

c = myQueue.poll();

} else {

result = super.evaluateSubExpression(super.getOperandValue(b), a, super.getOperandValue(c));

myQueue.offer(String.valueOf(result));

}

}

if (myQueue.size() == 1)

result = super.getOperandValue(myQueue.poll());

else {

a= myQueue.poll();

b = myQueue.poll();

c = myQueue.poll();

}

}

return result;

}

}

}

public class PostfixExpression extends Expression {

// Feel free to create other private/protected members, methods, or constructors.

/**

* This constructor receives a String containing the expression.

* It will call the constructor for class Expression,

* passing in the expression text

*/

public PostfixExpression(String expression) {

// Remember the super constructor // This constructor receives a String containing the expression text. It will invoke the constructor for class Expression, passing in the expression text.

super(expression);

}

@Override

/** 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.

* @return true if conditions are met

*/

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.

*/

boolean result = false;

int operands = 0;

int operators = 0;

ArrayList list = super.getTokens();

for (int i = 0; i < list.size(); i ++) {

if(super.isOperand(list.get(i))) {

while (operands !=2){

operands++;

}

}

if(super.isOperator(list.get(i))) {

while(operators != 1) {

operators++;

}

}

}

for( int i = 0; i < list.size(); i++) {

if(super.isOperator(list.get(list.size()-1)) &&

super.isOperand(list.get(0))&& super.isOperand(list.get(1)) && operands +1 == operators){

result = true;

} else

result = false;

} return result;

}

@Override

/**

* 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

*/

public double evaluate() {

double operand2;

double operand1;

String option;

double result = 0;

if(!isLegal())

throw new ArithmeticException();

Stack list = new Stack();

for(int i = 0; i < super.tokens.size()-1; i++) {

double value = Double.parseDouble(super.tokens.get(i));

list.push(value);

if(list.size() < 3) {

throw new ArithmeticException();

}

if(super.isOperand(Double.toString(value))) {

list.push(value);

}

if(super.isOperator(Double.toString(value))){

if(list.size() >= 2) {

operand2=list.pop();

operand1 = list.pop();

option = Double.toString(value);

result = super.evaluateSubExpression(operand1, option

, operand2);

list.push(result);

}

else {

throw new ArithmeticException();

}

} if(value == list.get(list.size()) &&list.size() == 1) {

return list.pop();

}else

throw new ArithmeticException();

}

return result;

}

}

public abstract class Expression {

// Feel free to modify

protected String expression;

protected ArrayList tokens;

/**receives a String containing the expression text, break the expressions into tokens

* and store the resulting String array into the data member tokenList.

* @param expression

*/

public Expression(String expression){

ArrayList newToken = new ArrayList();

String[] tokenList = expression.split(" ");

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

newToken.add(tokenList[i]);

}

}

/**

* @return the expression string

*/

public String getExpression() {

return expression;

}

/**

* @return the token list

*/

public ArrayList getTokens() {

return tokens;

}

/** determines if the String is a valid operand

* @param token

* @return true if the String parameters is a valid operand

*/

protected static boolean isOperand(String token) {

boolean result = false;

for(int i = 0; i < token.length()-1; i++) {

if(token.indexOf(i) != 0) {

result = false;

}

else {

result = true;

}

}

return result;

}

/** determines if String token is an operator

* @param token

* @return true if the String parameter contains one of +, -, *, / or %.

*/

protected static boolean isOperator(String token) {

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

return true;

}

else

return false;

}

/** given a String containing a valid operand

* this method returns the value of the operand as type double.

* @param token

* @return Double operand

* @throws NumberFormatException

*/

protected static double getOperandValue(String token) throws NumberFormatException {

if(!isOperand(token)) {

throw new NumberFormatException();

}else {

return Double.parseDouble(token);

}

}

/** This method evaluates a subexpression as operand1 operator operand2

* and returns the result as type double.

* @param operand1

* @param operator

* @param operand2

* @return result

*/

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

if( operator.equals("-")) {

return operand1 - operand2;

}

else if(operator.equals("+")) {

return operand1 + operand2;

}

else if(operator.equals("*")) {

return operand1 * operand2;

}

else if(operator.equals("/")) {

return operand1 / operand2;

} else {

return operand1 % operand2;

}

}

mport 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;

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions

Question

Is there any formal training for teaching?

Answered: 1 week ago