Question: Please complete the following: //--------------------------------------------------------------------------------------- //SUBOPERATOR CLASS /** * Represents the subtraction operator which is a specific type of binary operator. */ ??? //------------------------------------------------------------------------------------------ //VIEW






Please complete the following:
//---------------------------------------------------------------------------------------
//SUBOPERATOR CLASS
/** * Represents the subtraction operator which is a specific type of binary operator. */ ???
//------------------------------------------------------------------------------------------
//VIEW CLASS
package p04;
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField;
/** * The View class implements the GUI. */ public class View extends JFrame implements ActionListener {
public static final int FRAME_WIDTH = 500; public static final int FRAME_HEIGHT = 180;
// Declare instance variables private JButton mClearButton; private JButton mEvalButton; private JTextField mInputText; private JButton mExitButton; private Main mMain; private JLabel mResultLabel;
/** * View() * * The View constructor creates the GUI interface and makes the frame * visible at the end. */ public View(Main pMain) { // Save a reference to the Main object pMain in mMain. ? ? ? // PSEUDOCODE: // Declare and create a JPanel named panelLabel using the default FlowLayout layout manager. // Create mResultLabel as a JLabel initialized to the empty string "" // Add mResultLabel to panelLabel ? ? ? // PSEUDOCODE: // Declare and create a JPanel named panelInput using the default FlowLayout layout manager. // Create mInputText as a JTextField initialized to 40 columns wide // Add mInputText to panelInput ? ? ? // PSEUDOCODE: // Create a JPanel named panelButtons using FlowLayout. // Create the Clear button mClearButton. // Make this View the action listener for mClearButton. // Add the Clear button to the panel. // Repeat the three above statements for the Evalute button. // Repeat the three above statements for the Exit button. ? ? ? // PSEUDOCODE // Create a JPanel named panelMain using a vertical BoxLayout. // Add some vertical glue to panelMain // Add panelLabel to panelMain. // Add panelInput to panelMain. // Add panelButtons to panelMain. ? ? ? setTitle("Kalkutron-9001"); setSize(FRAME_WIDTH, FRAME_HEIGHT); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(panelMain); setVisible(true); }
/** * actionPerformed() * * Called when one of the JButtons is clicked. Detects which button was * clicked and handles it. * * PSEUDOCODE: If the source of the event was mClearbutton Then Call clear() * ElseIf the source of the event was mEvalButton Then Call evaluate() * ElseIf the source of the event was mExitButton Then Call exit() on mMain. * End If */ ???
/** * clear() is called when the Clear button is clicked. Set the text in mInputText and mResultLabel to the * empty strings "". */ ???
/** * evaluate() is called when the Evaluate button is clicked. * * PSEUDOCODE: * Retrieve the text string from mInputText * Declare and create an Expression object named expr passing the text string to the ctor * Call expr.evaluate() and assign the return value a Double object named result * Display result in mResultLabel (call toString on result) */ ???
/** * messageBox() */ public void messageBox(String pMessage) { JOptionPane.showMessageDialog(this, pMessage, "Message", JOptionPane.PLAIN_MESSAGE); }
}
//------------------------------------------------------------------------------------------
//OPERAND CLASS
/** * An operand is a numeric value represented as a Double. */ ???
//-------------------------------------------------------------------------------------------
//EXPRESSION CLASS
/** * Represents an infix expression to be evaluated. */ public class Expression {
/** * A queue which stores the tokens of the infix expression in the order in which they were input. */ Queue mTokenQueue;
/** * Expression(String) * * pExprStr is a string representing an infix expression, such as "(1 + 2) * -3". This ctor uses the * Tokenizer class to break the string into Token objects which are stored in the token queue instance * variable. * * PSEUDOCODE: * Create a new Queue object and pass it to setTokenQueue (this initializes mTokenQueue) * Declare and create a Tokenizer object named tokenizer passing pExprStr to the ctor * Declare a Token object named prevToken initialized to null * -- Read the first token * Declare a Token object named token and assign the return value from tokenizer.nextToken() to it * -- Keep reading tokens until tokenizer.nextToken() returns null * While token is not null Do * -- Check for and handle the negation operator. * If token instanceof SubOperator Then * token = negationCheck(token, pToken) * End if * -- Add the token to the queue. * Call getTokenQueue().enqueue(token) * prevToken = token * -- Read the next token. * token = call tokenizer.nextToken() * End While */ ???
/** * Evaluates the expression and returns the result as a Double. * * PSEUDOCODE: * Declare and create a Stack object named operatorStack * Declare and create a Stack object named operandStack * While mTokenQueue is not empty Do * Declare and create a Token object named token assigning getTokenQueue().dequeue() to it * If token instanceof Operand Then * Push token onto the operand stack (type cast token to Operand) * ElseIf token instanceof LeftParen Then * Push token onto the operator stack (type cast token to LeftParen) * ElseIf token instanceof RightParen Then * While the operator on the top of the operator stack is not an instanceof LeftParen Do * Call topEval(operatorStack, operandStack) * End While * Pop the top operator from the operator stack -- removes the LeftParen * Else * Declare Operator object named operator and assign token to it (type cast to Operator) * While keepEvaluating(operatorStack, operator) is true Do * Call topEval(operatorStack, operandStack) * EndWhile * Push operator onto the operator stack * End If * End While * While the operator stack is not empty Do * Call topEval(operatorStack, operandStack) * End While * Pop the top Operand from the operand stack and return its value (call getValue() on the Operand). */ ???
/** * Accessor method for mTokenQueue. */ protected Queue getTokenQueue() { return mTokenQueue; }
/** * Returns true when we need to pop the operator on top of the operator stack and evaluate it. If the stack * is empty, returns false since there is no operator to pop. Otherwise, return true if the operator on top * of the operator stack has stack precedence greater than or equal to the normal precedence of pOperator. */ private boolean keepEvaluating(Stack pOperatorStack, Operator pOperator) { if (pOperatorStack.isEmpty()) return false; else return pOperatorStack.peek().stackPrecedence() >= pOperator.precedence(); }
/** * Since the negation and subtraction operators look the same we can identify negation when: * * 1. The previous pToken is null (negation can be the first operator in an expression but sub cannot) * 2. Or if the previous pToken was a binary operator (sub cannot be preceded by another binary operator) * 3. Or if the previous pToken was a left parenthesis (sub cannot be preceded by a left paren) * * This method determines if pToken is really a negation operator rather than a subtraction operator, and if * so, will return a negation operator pToken. If pToken represents subtraction, then we simply return pToken. */ private Token negationCheck(Token pToken, Token pPrevToken) { if (pPrevToken == null || pPrevToken instanceof BinaryOperator || pPrevToken instanceof LeftParen) { pToken = new NegOperator(); } return pToken; }
/** * Mutator method for mTokenQueue. */ protected void setTokenQueue(Queue pTokenQueue) { mTokenQueue = pTokenQueue; }
/** * topEval() * * Evaluates the "top" of the stack. If the top operator on the operator stack is a unary operator, we pop * one operand from the operand stack, evaluate the result, and push the result onto the operand stack. If * the top operator on the operator stack is a binary operator, we pop two operands from the operand stack, * evaluate the result of the operation, and push the result onto the operand stack. * * PSEUDOCODE: * Declare and create Operand object named right = Call pOperandStack.pop() * Declare and create Operator object named operator = Call pOperatorStack.pop() * If operator instanceof UnaryOperator Then * Typecast operator to UnaryOperator and call evaluate(right) on it * Push the returned Operand from the above statement onto the operand stack * Else * Declare and create Operand object named left = Call pOperandStack.pop() * Typecast operator to BinaryOperator and call evaluate(left, right) on it * Push the returned Operand from the above statement onto the operand stack * End If */ ???
}
Background In the lecture notes and video lecturea fo Stacks and Queves : Sectiona we discussed an application that evaluates an arithmetic resuon witten in infix notation such a: (1--2)(3 5) Infx notation ia the uaual algebraic notation that we are ell iamiliar with wheze a binary opertor a binary opezator ia an operator that has two operandal in written between the left-hand and right-hand operands. For example, in the expression above, the left-hand operand of the eubtraction operator -1 nnd the right-hand operand i*-2 Some operators, such- the negation operato, are unary operatoa meening there ia only one operand (nione). For negstion, the operanda written to the right of the negation opezator. Therefore, thiexprexion contam aix operatoes: negation, aubtraction. negation, maltiplication, negation, and division. In the algorithm that evaluates the expresionre as treat a left parentheaio the eveluation we bare to push left parentheoes onto the operator stack. an operato, which it n not, but duma en inflx arithmetic expreaaaon, each operator hea precedence level-which for a left Parenthema. ia different when it ia the operator stack oppoeed to when it is not thie will become clear Then you read the trace of the algorithm for the above expression; eee poge 3): Operator Normal Precedence LevStack Precedence Level Right parenthces really don't have precedence because they are not pushed on the operator stack, but we asnign thema precedence level of 1 for conaistency. The algorithm discussed in the notes did not handle the negation operator soI bae modised it to hendle negation. Here is the reved algorithm Method evaluate In: pEran infix epreaio Returns Doule Create operatorStack-Stores Operators Create operandStack - Storts Operands While end of pExp haa not been reched Do Scan next token in pEpThe type of token ia Token If token is on operand Then Convert token to Operend abject named number operandtack puh namber) Elself token ia an Instanceof LetParen Then Comvert token to Lef Paren object named paren operatorStack.puparen) Elself taken i InstanceOf RtghtParen Then While not operatorStack peck) ie an InstanceOf Le Paren Do topErol operatorStack.pop) -Popa the Lef Paren Elself toen ia Negation, Addttion 5raction, ^ultiplication or Diton Then Comvert token to Operator object named operator While kecpEvaluating) return True Do topa perator Stackpust op) End while While not oStackE) Do topEval) Return operandSteck pop) End Method evelaete Method kee Eveluctinel Returns True oe False If operatorStack.isEmy Then Return False Else Return taekPrecederace(operetorStaek,peek))Precedence( operator) End Method keepEealuating Method topEa Returns Nothing right operendStackpop operator opertorStackpor) If operator is Negation Then opcrandStack pushi-ight Else le operandStack pop) If operator ia Adtion Then operndStack pusheftright) Elself operator is Subtraction Then operandstack pust left- ight Elself operator is Melp Then operandSteek pef right) Else operandStaek push teft /r right End Method topBorl Method pracedcece In: Operator pOperator) Returns Int If pOperator ia LeftPaen Then Return 5 EleIr pOperctor ia Negation Then Return 4 Elself pOperator in iplication ar Dsion Then Return 3 Elself pOperator is Addor Subtration Then Return 2 Else Return 1 End Method precedece Method stachPrecedcrce In: Operator pOperator Returns Int If pOperatoris LftParen Then Return 0 ElseIf pOperetor ia Negation Then Return d Eleelf pOperator is Mtiplicatton o Dison Then Return 3 Elself pOpertori Adddion or Subtraction Then Return 2 Else Return 1 End Method stactPrecederc Background In the lecture notes and video lecturea fo Stacks and Queves : Sectiona we discussed an application that evaluates an arithmetic resuon witten in infix notation such a: (1--2)(3 5) Infx notation ia the uaual algebraic notation that we are ell iamiliar with wheze a binary opertor a binary opezator ia an operator that has two operandal in written between the left-hand and right-hand operands. For example, in the expression above, the left-hand operand of the eubtraction operator -1 nnd the right-hand operand i*-2 Some operators, such- the negation operato, are unary operatoa meening there ia only one operand (nione). For negstion, the operanda written to the right of the negation opezator. Therefore, thiexprexion contam aix operatoes: negation, aubtraction. negation, maltiplication, negation, and division. In the algorithm that evaluates the expresionre as treat a left parentheaio the eveluation we bare to push left parentheoes onto the operator stack. an operato, which it n not, but duma en inflx arithmetic expreaaaon, each operator hea precedence level-which for a left Parenthema. ia different when it ia the operator stack oppoeed to when it is not thie will become clear Then you read the trace of the algorithm for the above expression; eee poge 3): Operator Normal Precedence LevStack Precedence Level Right parenthces really don't have precedence because they are not pushed on the operator stack, but we asnign thema precedence level of 1 for conaistency. The algorithm discussed in the notes did not handle the negation operator soI bae modised it to hendle negation. Here is the reved algorithm Method evaluate In: pEran infix epreaio Returns Doule Create operatorStack-Stores Operators Create operandStack - Storts Operands While end of pExp haa not been reched Do Scan next token in pEpThe type of token ia Token If token is on operand Then Convert token to Operend abject named number operandtack puh namber) Elself token ia an Instanceof LetParen Then Comvert token to Lef Paren object named paren operatorStack.puparen) Elself taken i InstanceOf RtghtParen Then While not operatorStack peck) ie an InstanceOf Le Paren Do topErol operatorStack.pop) -Popa the Lef Paren Elself toen ia Negation, Addttion 5raction, ^ultiplication or Diton Then Comvert token to Operator object named operator While kecpEvaluating) return True Do topa perator Stackpust op) End while While not oStackE) Do topEval) Return operandSteck pop) End Method evelaete Method kee Eveluctinel Returns True oe False If operatorStack.isEmy Then Return False Else Return taekPrecederace(operetorStaek,peek))Precedence( operator) End Method keepEealuating Method topEa Returns Nothing right operendStackpop operator opertorStackpor) If operator is Negation Then opcrandStack pushi-ight Else le operandStack pop) If operator ia Adtion Then operndStack pusheftright) Elself operator is Subtraction Then operandstack pust left- ight Elself operator is Melp Then operandSteek pef right) Else operandStaek push teft /r right End Method topBorl Method pracedcece In: Operator pOperator) Returns Int If pOperator ia LeftPaen Then Return 5 EleIr pOperctor ia Negation Then Return 4 Elself pOperator in iplication ar Dsion Then Return 3 Elself pOperator is Addor Subtration Then Return 2 Else Return 1 End Method precedece Method stachPrecedcrce In: Operator pOperator Returns Int If pOperatoris LftParen Then Return 0 ElseIf pOperetor ia Negation Then Return d Eleelf pOperator is Mtiplicatton o Dison Then Return 3 Elself pOpertori Adddion or Subtraction Then Return 2 Else Return 1 End Method stactPrecederc
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
