Question: import java.util.Stack; import java.util.StringTokenizer; public class Evaluator { private Stack operandStack; private Stack operatorStack; private StringTokenizer tokenizer; private static final String DELIMITERS = +-*^/; public

import java.util.Stack; import java.util.StringTokenizer; public class Evaluator { private Stack operandStack; private Stack operatorStack; private StringTokenizer tokenizer; private static final String DELIMITERS = "+-*^/"; public Evaluator() { operandStack = new Stack<>(); operatorStack = new Stack<>(); } public int eval( String expression ) { String token; // The 3rd argument is true to indicate that the delimiters should be used // as tokens, too. But, we'll need to remember to filter out spaces. this.tokenizer = new StringTokenizer( expression, DELIMITERS, true ); // initialize operator stack - necessary with operator priority schema // the priority of any operator in the operator stack other than // the usual mathematical operators - "+-*/" - should be less than the priority // of the usual operators while ( this.tokenizer.hasMoreTokens() ) { // filter out spaces if ( !( token = this.tokenizer.nextToken() ).equals( " " )) { // check if token is an operand if ( Operand.check( token )) { operandStack.push( new Operand( token )); } else { if ( ! Operator.check( token )) { System.out.println( "*****invalid token******" ); throw new RuntimeException("*****invalid token******"); } // TODO Operator is abstract - these two lines will need to be fixed: // The Operator class should contain an instance of a HashMap, // and values will be instances of the Operators. See Operator class // skeleton for an example. Operator newOperator = new Operator(); while (operatorStack.peek().priority() >= newOperator.priority() ) { // note that when we eval the expression 1 - 2 we will // push the 1 then the 2 and then do the subtraction operation // This means that the first number to be popped is the // second operand, not the first operand - see the following code Operator oldOpr = operatorStack.pop(); Operand op2 = operandStack.pop(); Operand op1 = operandStack.pop(); operandStack.push( oldOpr.execute( op1, op2 )); } operatorStack.push( newOperator ); } } } // Control gets here when we've picked up all of the tokens; you must add // code to complete the evaluation - consider how the code given here // will evaluate the expression 1+2*3 // When we have no more tokens to scan, the operand stack will contain 1 2 // and the operator stack will have + * with 2 and * on the top; // In order to complete the evaluation we must empty the stacks (except // the init operator on the operator stack); that is, we should keep // evaluating the operator stack until it only contains the init operator; // Suggestion: create a method that takes an operator as argument and // then executes the while loop. return 0; } }

---------------------------------------------------------------------------------

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class EvaluatorDriver {
/**
* Driver class that uses Evaluator to evaluate expressions.
* The expressions can either be given as a command line argument
* OR typed in at the keyboard. If you wish to type in expressions
* give NO commmand line arguments. Otherwise you may give a list of
* strings as a command line argument and the driver will run all strings
* in that list.
*
* @param args command line arguments.
*/
public static void main(String... args){
BufferedReader input;
String exp;
int res;
Evaluator ev = new Evaluator();
if(args.length == 0){
try {
input = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.print("Enter an Expression: ");
exp = input.readLine();
res = ev.eval(exp);
System.out.printf("Expression : %s , Result %6d ", exp, res);
}
}catch (Exception ex){
System.out.println(ex.getMessage());
}
}else{
for(String ex : args) {
res = ev.eval(ex);
System.out.printf("Expression : %s , Result: %-6d ", ex, res);
}
}
}

}

----------------------------------------------------------------------------

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class EvaluatorUI extends JFrame implements ActionListener {
private TextField txField = new TextField();
private Panel buttonPanel = new Panel();
// total of 20 buttons on the calculator,
// numbered from left to right, top to bottom
// bText[] array contains the text for corresponding buttons
private static final String[] bText = {
"7", "8", "9", "+", "4", "5", "6", "- ", "1", "2", "3",
"*", "0", "^", "=", "/", "(", ")", "C", "CE"
};
/**
* C is for clear, clears entire expression
* CE is for clear expression, clears last entry up until the last operator.
*/
private Button[] buttons = new Button[bText.length];
public static void main(String argv[]) {
EvaluatorUI calc = new EvaluatorUI();
}
public EvaluatorUI() {
setLayout(new BorderLayout());
this.txField.setPreferredSize(new Dimension(600, 50));
this.txField.setFont(new Font("Courier", Font.BOLD, 28));
add(txField, BorderLayout.NORTH);
txField.setEditable(false);
add(buttonPanel, BorderLayout.CENTER);
buttonPanel.setLayout(new GridLayout(5, 4));
//create 20 buttons with corresponding text in bText[] array
Button bt;
for (int i = 0; i < EvaluatorUI.bText.length; i++) {
bt = new Button(bText[i]);
bt.setFont(new Font("Courier", Font.BOLD, 28));
buttons[i] = bt;
}
//add buttons to button panel
for (int i = 0; i < EvaluatorUI.bText.length; i++) {
buttonPanel.add(buttons[i]);
}
//set up buttons to listen for mouse input
for (int i = 0; i < EvaluatorUI.bText.length; i++) {
buttons[i].addActionListener(this);
}
setTitle("Calculator");
setSize(400, 400);
setLocationByPlatform(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent arg0) {
// You need to fill in this fuction
}

}

--------------------------------------------------------------------------------

/** * Operand class used to represent an operand * in a valid mathmetical expression. */ public class Operand { /** * construct operand from string token. */ public Operand( String token ) { } /** * construct operand from integer */ public Operand( int value ) { } /** * return value of opernad */ public int getValue() { return 0; } /** * Check to see if given token is a valid * operand. */ public static boolean check( String token ) { return false; }

------------------------------------------------------------------------------------------

import java.util.HashMap;
public abstract class Operator {
// The Operator class should contain an instance of a HashMap
// This map will use keys as the tokens we're interested in,
// and values will be instances of the Operators.
// ALL subclasses of operator MUST be in their own file.
// Example:
// Where does this declaration go? What should its access level be?
// Class or instance variable? Is this the right declaration?
// HashMap operators = new HashMap();
// operators.put( "+", new AdditionOperator() );
// operators.put( "-", new SubtractionOperator() );
public abstract int priority();
public abstract Operand execute(Operand op1, Operand op2 );
/**
* determines if a given token is a valid operator.
* please do your best to avoid static checks
*/
public static boolean check( String token ) {
return false;
}

}

------------------------------

Requirements: You will be provided with an almost complete version of the Evaluator class (Evaluator.java). You should program the utility classes it uses - Operand and Operator - and then follow the suggestions in the code to complete the implementation of the Evaluator class. The Evaluator implements a single public method, eval, that takes a single String parameter that represents an infix mathematical expression, parses and evaluates the expression, and returns the integer result. An example expression is 2 + 3 * 4, which would be evaluated to 14. The expressions are composed of integer operands and operators drawn from the set +, -, *, /, ^, (, and ). These operators have the following priorties: (+,- #1, *,/ #2, ^ #3)

The algorithm that is partially implemented in eval processes the tokens in the expression string using two Stacks; one for operators and one for operands (algorithm reproduced here from http://csis.pace.edu/~murthy/ProgrammingProblems/16_Evaluation_of_infix_expression s):

* If an operand token is scanned, an Operand object is created from the token, and pushed to the operand Stack

* If an operator token is scanned, and the operator Stack is empty, then an Operator object is created from the token, and pushed to the operator Stack

* If an operator token is scanned, and the operator Stack is not empty, and the operators precedence is greater than the precedence of the Operator at the top of the Stack, then and Operator object is created from the token, and pushed to the operator Stack

* If the token is (, and Operator object is created from the token, and pushed to the operator Stack * If the token is ), the process Operators until the corresponding ( is encountered. Pop the ( Operator.

* If none of the above cases apply, process an Operator. Processing an Operator means to:

* Pop the operand Stack twice (for each operand - note the order!!)

* Pop the operator Stack

* Execute the Operator with the two Operands

* Push the result onto the operand Stack When all tokens are read, process Operators until the operator Stack is empty.

Requirement 1: Implement the above algorithm within the Evaluator class (this implementation need not be submitted, but it is strongly recommended that you begin with this version).

Requirement 2: Test this implementation with expressions that test all possible cases (you may use the included Unit Tests and Driver class to do this).

Requirement 3: Implement the following class hierarchy

* Operator must be an abstract superclass.

* boolean check( String token ) - returns true if the specified token is an operator

* abstract int priority() - returns the precedence of the operator

* abstract Operand execute( Operand operandOne, Operand operandTwo ) - performs a mathematical calculation dependent on its type * This class should contain a HashMap with all of the Operators stored as values, keyed by their token. An interface/public method should be created in Operator to allow the Evaluator (or other software components in our system) to look up Operators by token.

* Individual Operator classes must be subclassed from Operator to implement each of the operations allowed in our expressions

*Operand

* boolean check( String token ) - returns true if the specified token is an operand

* Operand( String token ) - Constructor

* Operand( double value ) - Constructor

* int getValue() - returns the integer value of this operand

Requirement 4: Reuse your Evaluator implementation in the provided GUI Calculator (EvaluatorUI.java). Additional Notes. Please use the following names for the operator classes operatornameOperator For example: AddOperator DivideOperator MultiplyOperator PowerOperator SubtractOperator

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!