package assignment;
/**
* CPS231 – Fall 2021
* Assignment 3 – Infix Evaluator using the Stack ADT
*
* February 6, 2021
*
* @author Adam Divelbiss
*
*/
public class Assignment03 {
public static void main(String[] args) {
// Evaluate the following expressions
// a=2,b=3,c=4,d=5,e=6
InfixEvaluator infixEvaluator = new InfixEvaluator();
infixEvaluator.setValue(‘a’, 2);
infixEvaluator.setValue(‘b’, 4);
infixEvaluator.setValue(‘c’, 3);
infixEvaluator.setValue(‘d’, 5);
System.out.println(“Testing infix expressions with:”);
System.out.println(” a = ” + infixEvaluator.valueOf(‘a’));
System.out.println(” b = ” + infixEvaluator.valueOf(‘b’));
System.out.println(” c = ” + infixEvaluator.valueOf(‘c’));
System.out.println(” d = ” + infixEvaluator.valueOf(‘d’));
System.out.println(“”);
testInfix(infixEvaluator, “a+b”, 6.0);
testInfix(infixEvaluator, “(a + b) * c”, 18.0);
testInfix(infixEvaluator, “a * b / (c – d)”, -4.0);
testInfix(infixEvaluator, “a / b + (c – d)”, -1.5);
testInfix(infixEvaluator, “a / b + c – d”, -1.5);
testInfix(infixEvaluator, “a^b^c”, 1.8446744073709552E19);
testInfix(infixEvaluator, “(a^b)^c”, 4096.0);
testInfix(infixEvaluator, “a*(b/c+d)”, 12.666666666666666);
testInfix(infixEvaluator, “e * (a – c) / (b – c)”, 0.0);
testInfix(infixEvaluator, “(b – c) * (a – c) / (b – c)”, -1.0);
System.out.println(“Done.”);
}
public static void testInfix(InfixEvaluator evaluator, String infixExpression, double expected)
{
final double TOLERANCE = 1.0e-9;
double result = evaluator.evaluate(infixExpression);
System.out.println(“Infix: “” + infixExpression + “”””””);
System.out.println(“”Result: “” + result);
if (Math.abs(result – expected) < TOLERANCE) {
System.out.println(“”TEST: OK””);
} else {
System.out.println(“”TEST: ERROR””);
}
System.out.println();
} // end testInfix
}
package assignment;
/**
* CPS231 – Fall 2021
* Assignment 03 – A class to evaluate infix expressions.
*
* @author adamdivelbiss
*
*/
public class InfixEvaluator {
/**
* private helper method to return the precedence value for a particular operator.
* @param operator
* @return
*/
private static int precedence(char operator) {
int result = -1;
switch (operator) {
case ‘(‘: case ‘)’: result = 0; break;
case ‘+’: case ‘-‘: result = 1; break;
case ‘*’: case ‘/’: result = 2; break;
case ‘^’: result = 3; break;
}
return result;
}
/**
* private helper method to compute the value of a basic infix operation
* @param operandOne
* @param operandTwo
* @param operator
* @return
*/
private static double compute(double operandOne