1 Introduction to Computation and Problem Solving Class 24: Case Study: Building a Simple Postfix Calculator Prof. Steven R. Lerman and Dr. V. Judson Harward.

Slides:



Advertisements
Similar presentations
INFIX, PREFIX, & POSTFIX EXPRESSIONS. Infix Notation We usually write algebraic expressions like this: a + b This is called infix notation, because the.
Advertisements

1 Introduction to Computation and Problem Solving Class 23: Introduction to Data Structures: Stacks and Queues Prof. Steven R. Lerman and Dr. V. Judson.
Graphical User Interfaces
Stack & Queues COP 3502.
The Model-View Approach in Java. OK, you’ve got “Hello World” running... What now?
Problem Solving 6 GUIs and Event Handling ICS-201 Introduction to Computing II Semester 071.
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Stacks - 3 Nour El-Kadri CSI Evaluating arithmetic expressions Stack-based algorithms are used for syntactical analysis (parsing). For example.
Computer Science 2 Data Structures V section 2 Recitation 1.
Arithmetic Expressions Infix form –operand operator operand 2+3 or a+b –Need precedence rules –May use parentheses 4*(3+5) or a*(b+c)
COSC 2006 Chapter 7 Stacks III
Stacks Example: Stack of plates in cafeteria.
Lecture 12 – ADTs and Stacks.  Modularity  Divide the program into smaller parts  Advantages  Keeps the complexity managable  Isolates errors (parts.
Arithmetic Expressions
Topic 15 Implementing and Using Stacks
Introduction to Stacks What is a Stack Stack implementation using arrays. Application of Stack.
Stacks.
Reverse Polish Notation (RPN) & Stacks CSC 1401: Introduction to Programming with Java Week 14 – Lecture 2 Wanda M. Kunkle.
Infix, Postfix, Prefix.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Stacks (Revised and expanded from CIT 591). What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on.
CST Razdan et al Razdan with contribution from others 1 Chapter 6 Stacks Anshuman Razdan Div of Computing.
Topic 15 Implementing and Using Stacks
Exam 1 –Monday June 25 th –open Book / Open Notes –No Electronic Devices (calculators, laptops, etc) –Room Number: W –Time: 5:30pm to 8:00pm.
Topic 3 The Stack ADT.
Data Structures Lecture : Stacks (Infix, Postfix and Prefix Expressions) Azhar Maqsood NUST Institute of Information Technology (NIIT)
Data Structures: CSCI 362 – Stack Implementation Data Structures: CSCI 362 – Stack Implementation lecture notes adapted from Data Structures with C++ using.
Lecture Objectives To understand how Java implements a stack To learn how to implement a stack using an underlying array or linked list Implement a simple.
CSC 205 Programming II Postfix Expressions. Recap: Stack Stack features Orderly linear structure Access from one side only – top item Stack operations.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Data Structures and Algorithms
Introduction to Computation and Problem Solving Class 15: Constructing Interfaces with Swing Prof. Steven R. Lerman and Dr. V. Judson Harward 1.
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
COMP 121 Week 13: Stacks. Objectives Learn about the stack data type and how to use its four methods: push, pop, peek, and empty Understand how Java implements.
Information and Computer Sciences University of Hawaii, Manoa
Chapter 7 Stacks. © 2004 Pearson Addison-Wesley. All rights reserved 7-2 The Abstract Data Type: Developing an ADT During the Design of a Solution Specifications.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
Basic Data Structures Stacks. A collection of objects Objects can be inserted into or removed from the collection at one end (top) First-in-last-out.
Stacks An Abstract Data Type. Restricted Access Unlike arrays, stacks only allow the top most item to be accessed at any time The interface of a stack.
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
CHP-3 STACKS.
Reverse Polish Notation Written by J.J. Shepherd.
Stacks Chapter 5 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures and Abstractions with Java, 4e Frank Carrano.
Review Use of Stack Introduction Stack in our life Stack Operations
Stacks Access is allowed only at one point of the structure, normally termed the top of the stack access to the most recently added item only Operations.
Revised based on textbook author’s notes.
COMPSCI 107 Computer Science Fundamentals
Infix to postfix conversion
MEMORY REPRESENTATION OF STACKS
Review: Java GUI Programming
ASTs, Grammars, Parsing, Tree traversals
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Visit for more Learning Resources
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Stacks, Queues, and Deques
Lecture No.07 Data Structures Dr. Sohail Aslam
Infix to Postfix Conversion
Queue Applications Lecture 31 Mon, Apr 9, 2007.
Infix to Postfix Conversion
Topic 15 Implementing and Using Stacks
Queue Applications Lecture 31 Tue, Apr 11, 2006.
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
Stacks A stack is an ordered set of elements, for which only the last element placed into the stack is accessible. The stack data type is also known as.
© 2016 Pearson Education, Ltd. All rights reserved.
CHAPTER 3: Collections—Stacks
Presentation transcript:

1 Introduction to Computation and Problem Solving Class 24: Case Study: Building a Simple Postfix Calculator Prof. Steven R. Lerman and Dr. V. Judson Harward

2 Goals To build a calculator to show how to divide functionality up into meaningful classes To introduce two useful software patterns: –Model/View/Controller –Finite State Machine

3 Infix vs Postfix Notation Most early scientific calculators used an expression notation called postfix rather than the infix notation that we are used to. Infix: (13.5 – 1.5)/( ) Postfix: /

4 Infix vs Postfix, II Postfix notation gets rid of the parentheses that are necessary to determine precedence and evaluation order in infix notation. Postfix is scanned left to right. Operators are evaluated as soon as they are encountered. If we remove the parentheses from our infix version, we get the ambiguous 13.5 –1.5 / Is that (13.5 – 1.5)/( ) or 13.5 – (1.5 / 3.4) ?

5 Postfix and Stacks The best way to interpret postfix notation is with a stack. Whenever the next item is a number, we push it on the stack. When the next item is an operator, –the appropriate number of operands for the operator are popped off the stack, –the operator is applied, and –the result is pushed back on the stack.

6 Evaluating Postfix Infix: (13.5 – 1.5)/( ) Postfix: / Postfix ItemStack / 3.0

7 Software Patterns A software pattern is a design of a solution to a recurring software problem. Patterns are independent of implementation language. They are more general and flexible than algorithms and data structures.

8 Model/View/Controller (MVC) Model/View/Controller is a useful pattern for the design of interactive programs with a GUI MVC has a long history going back to one of the earliest OO languages, Smalltalk. MVC has strongly affected the Java® event model. –Event sources are part of the view. –Event listeners are part of the controller.

9 MVC and our Calculator The view is the class ( Calculator ) that presents the user interface, the keypad and display. The controller is the class ( Calculator Controller ) that interacts with the user, that processes events and updates the calculator without worrying about the details of the display. The model is the class ( CalculatorModel ) that handles computation, the CPU and memory of the calculator, if you want to think of it that way. The application ( CalculatorApp ), of course, pulls these pieces together with a main().

10 MVC in the Calculator View display updates Model ActionEvents Controller results operations

11 Calculator GUI 2.1 JPanel contains JLabel 2. Reusable subclass of JPanel 1. Overall JFrame JButton subclass KeyButton 2.2 JPanel subclass Keypad

12 Calculator, 1 public class Calculator extends javax.swing.JPanel implements ActionListener { class Keypad extends JPanel {... } class KeyButton extends JButton {... } static final String L_CE = "CE"; static final String C_CE = "-1"; static final int I_CE = -1;... public static boolean isDigit( int eT ) { return( eT>= 0 && eT <= 9 ); } public static boolean isOp( int eT ) { return( eT = I_ADD ); }

13 Calculator Key Codes digits operations: push, +, etc

14 Calculator, KeyButton class KeyButton extends JButton { KeyButton( String l, ActionListener a ) { super( l ); setBackground( Color.lightGray ); addActionListener( a ); } KeyButton( String l, Color f, ActionListener a ) { this( l, a ); setForeground( f ); } KeyButton( String l, String c, Color f, ActionListener a ) { this( l, a ); setForeground( f ); setActionCommand( c ); }

15 Calculator, KeyPad class Keypad extends JPanel { Keypad() { setLayout( new GridLayout( 0, 5, 2, 2 ));... add( new KeyButton( L_CE, C_CE, Color.green, Calculator.this )); add( new KeyButton( "1", Color.black, Calculator.this ));... }

16 Calculator, 2 private JLabel display = null; public void setDisplay( String s ) { display.setText( s ); } public void clearDisplay() { display.setText( EMPTYSTR ); } public void actionPerformed( ActionEvent e ) { if ( controller != null ) controller.actionPerformed( e ); }

17 CalculatorController : the Controller This class's task is the hardest because it is the messiest. Its job is to interpret the user's button presses, update the display, and use the model to perform all the calculations. The CalculatorController is the class that connects the other parts of the pattern. It knows about both the view and the model, while the view knows only about the controller, and the model is used by the controller, but never uses (calls) it back.

18 Controller and Model Is the calculator display a copy of what is on the top of the stack? What goes on the stack? Double s? When we enter a number on the calculator do we want to think of the intermediate values as doubles or as characters? To avoid round off error, we treat the display as a String (actually a StringBuffer ) that has to be pushed onto the stack as a Double.

19 The Controller and State The other difficulty for the controller is that its behavior depends on what has already happened. For instance, –if the user starts entering a new number by clicking 3 the controller should assume that the user is entering an integer. –But if the user then hits., the controller must now assume a floating point number. –If the user then hits a second., that's an error, because the controller has already seen a decimal point. The behavior of the controller depends on previous state.

20 Finite State Machines This kind of situation is frequently best handled by another design pattern called a finite state machine or finite state automaton. A FSM is an object that can occupy one of a finite number of states. One of these states, called the start state, specifies the state of a freshly created instance of the FSM. The FSM accepts input tokens or events, one at a time. The FSM specifies a transition to a new state for each possible state and input token. The transition often specifies an action, which is what makes the FSM useful.

21 The CalculatorController FSM Start State POP,C,CE CLEARED INTEGER_VFLOAT_V ERROR PUSH,OP,SIGN PUSH, C,CE SIGN OP = { /,*,-,+ } PUSH,C,CE POINT,OP,POP SIGN, OP,POP POINT

22 FSM in Operation Let's follow the example, 3.14 PUSH 2 * (or, in infix, 3.14 * 2 ), through the FSM: 1.We start in the CLEARED state (the start state) 2.3 puts us into the INTEGER_V state 3.. transitions us to the FLOAT_V state 4.1 and 4 just add to the number in the accumulator while remaining in FLOAT_V 5.PUSH transitions us to CLEARED and pushes the value 3.14 onto the stack in the model

23 FSM in Operation, transitions us to INTEGER_V and starts a new number in the accumulator 7.* is an operation, and implicitly pushes 2 onto the model stack. It also transitions us momentarily to CLEARED, then causes the controller to invoke the mul() method on the model returning the result The returned result is sent to the accumulator putting us back in FLOAT_V.

24 FSM in Operation, 3 CLEARED INTEGER_VFLOAT_V ERROR 1. Start here 2. Transition on 3 3. The. takes us to FLOAT_V

25 FSM in Operation, 4 CLEARED INTEGER_VFLOAT_V ERROR 5. PUSH transitions us to CLEARED and pushes 3.14 onto the stack 4. 1 and 4 just add to the float value

26 FSM in Operation, 5 CLEARED INTEGER_VFLOAT_V ERROR 6. 2 transitions us to INTEGER_V and starts a new number 7. * implicitly pushes 2 onto the stack. It also causes the controller to invoke the mul() method on the model returning the result 6.28 putting us back in FLOAT_V.

27 CalculatorController, 1 public class CalculatorController implements ActionListener { private Calculator calculator; private CalculatorModel model; private StringBuffer acc; private int state = CLEARED; private boolean neg = false; private final int CLEARED = 0; private final int INTEGER_V = 1; private final int FLOAT_V = 2; private final int ERROR = 3;

28 CalculatorController, 2 public void actionPerformed( ActionEvent e ) { String eStr = e.getActionCommand(); int eType = Integer.parseInt( eStr ); if ( state == ERROR ) { // The only way to exit error is a general CLEAR if ( eType == Calculator.I_C ) { reset(); } else return; }

29 CalculatorController, 3 if ( eType == Calculator.I_CE ) clearEntry(); else if ( eType == Calculator.I_C ) reset(); else { switch ( state ) { case CLEARED: if ( Calculator.isDigit( eType ) ) { state = INTEGER_V; acc.append( eStr ); } else if ( Calculator.isOp( eType )) doOp( eType ); else if ( eType == Calculator.I_POINT ) { state = FLOAT_V; acc.append ( "0." ); } else error(); break; //... cases INTEGER_V, FLOAT_V

30 CalculatorController, doOp() private void doOp( int eT ) {... try { if ( state != CLEARED ) doPush(); switch( eT ) { case Calculator.I_DIV: setAcc( model.div() ); break; case Calculator.I_MUL:... case Calculator.I_SUB:... case Calculator.I_ADD:... } } catch ( EmptyStackException e ) { error(); }

31 CalculatorModel Overview After working with the controller, the model seems simple although it is where the computation occurs. Each operation method, div(), mul(), sub(), and add(), is careful to get the order of the arguments popped off the stack correct. All these methods and CalculatorModel.pop() can throw an EmptyStackException because they each invoke Stack.pop(). The methods don't catch the exception so it is passed back to the calling routine in a way that we will examine in a later lecture.

32 CalculatorModel Code public class CalculatorModel { private Stack stack = new ArrayStack(); public void push( double d ) { stack.push( new Double( d ) ); } public double pop() throws EmptyStackException { return (( Double ) stack.pop()).doubleValue(); } public double div() throws EmptyStackException { double bot = pop(); double top = pop(); return top / bot; }... Java® is a trademark or registered trademark of Sun Microsystems, Inc. in the United States and other countries.