Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

image text in transcribedimage text in transcribedimage text in transcribed

EVALUATOR:

import java.util.*;

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

// TODO Operator is abstract - this will need to be fixed:

// operatorStack.push( new Operator( "#" ));

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******" );

System.exit( 1 )}

// TODO Operator is abstract - this line 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( token );

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 12

// 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 empty

// Suggestion: create a method that takes an operator as argument and

// then executes the while loop; also, move the stacks out of the main

// methoD

return 0;}}

EVALUATOR TESTER: /**

 * Class to help test your Evaluator:
 * javac EvaluatorTester
 * java EvaluatorTester "1+2" "3*5"
 */ public class EvaluatorTester {
 public static void main(String[] args) {
 Evaluator evaluator = new Evaluator();
for ( String arg : args ) {
 System.out.format( "%s = %d ", arg, evaluator.eval( arg ) );}}}

EVALUATOR UI:

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"};
 private Button[] buttons = new Button[ bText.length ];
public static void main(String argv[]) {
 EvaluatorUI calc = new EvaluatorUI();}
public EvaluatorUI() {
 setLayout( new BorderLayout() );
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
 for ( int i = 0; i  
 buttons[ i ] = new Button( bText[ i ]);
 }//add buttons to button panel
 for (int i=0; i 
 buttonPanel.add( buttons[ i ]);}
//set up buttons to listen for mouse input
 for ( int i = 0; 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:

public class Operand {
public Operand( String token ) {}
public Operand( int value ) {}
public int getValue() {}
public static boolean check( String token ) {}}

OPERATOR:

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.
// 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 );
public static boolean check( String token ) {}}

Overview The purpose of this assignment is to practice object oriented design to create two programs: 1. An object that evaluates mathematical expressions 2. A GUI around the artifact from (1) You are provided with a project skeleton, which will be automatically cloned into your github repository when you begin the assignment via this link: https:// classroom.github.com/a/Lb9noyKl. Submission Your assignment will be submitted using github. Only the "main" branch of your repository will be graded. Late submission is determined by the last commit time on the "main" branch. You are required to submit a documentation PDF named "documentation.pdf" in a "documentation" folder at the root of your project. Please refer to the documentation requirements posted on iLearn. Organization and appearance of this document is critical. Please use spelling and grammar checkers - your ability to communicate about software and technology is almost as important as your ability to write software! Requirements You will be provided with a code skeleton for the Evaluator class (Evaluator.java). You should program the utility classes it uses - Operand and Operator - and then follow the algorithm described below 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 +, -;*,1,^, (, and ). These operators have the following precedence: Operator Priority +,- 2 3 A 4 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/Programming Problems/ 16 Evaluation of infix_expressions): 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 operator's precedence is greater than the precedence of the Operator at the top of the Stack, then an Operator object is created from the token, and pushed to the operator Stack * If the token is (, an Operator object is created from the token, and pushed to the operator Stack * If the token is), then 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. Requirement 2: Test this implementation with expressions that test all possible cases (you may use the included EvaluatorTest class to do this, or create JUnit tests). 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 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, and should be properly organized in your project * Operand * boolean check( String token) - returns true if the specified token is an operand Operand( String token ) - Constructor * Operand( int value ) - Constructor * int getValue() - returns the integer value of this operand Requirement 4: Reuse your Evaluator implementation in the provided GUI Calculator (EvaluatorUl.java). Appendix A: Rubric (Next page)

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

Recommended Textbook for

Databases A Beginners Guide

Authors: Andy Oppel

1st Edition

007160846X, 978-0071608466

More Books

Students also viewed these Databases questions

Question

Find dy/dx if x = te, y = 2t2 +1

Answered: 1 week ago