Tutorial: A Basic Calculator II


by
Ronald S. Holland
Total Application Works
RonHolland@sumtotalz.com







To visit my site



HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript ]


To contact us

© 2002 - 2016 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following HTML page into a file or send this page to a friend.)
    <html>
    <title>Example of a link </title>
    <body>
    <table border>
    <a
    href="http://www.sumtotalz.com/TotalAppsWorks/Calc_All/BasicCalc_Tut_II.html">

    How to Create a Basic Calculator II Application </a>
    </table>
    </body>
    </html>
    Source
    Screenshot
  • On-site classes can be arranged in Java and C++. Send all inquiries to:
    RonHolland@sumtotalz.com


  1. Java Table of contents
  2. 2nd Java Cup
  3. Pie Chart I
  4. Pie/Bar Chart IB
  5. Pie/Bar Chart II
  6. Pie/Bar Chart III
  7. A Basic Calculator
  8. Linked Lists
  9. Linked List II
  10. Linked List III
  11. Linked List IV
  12. Hardware Store I
  13. Hardware Store II
  14. Hardware Store III
  15. Client/Server
  16. Client/Server II
  17. Client/Server III
  18. Client/Server IV
  19. Multithreaded Client/Server
  20. Multithreaded Client/Server II
  21. Multithreaded Client/Server III
  22. Basic Calculator II
  23. Basic Calculator III
  • Introduction
  • Requirements
  • What is the Holland's OOP Programming Design Model?
  • Application Template
  • Let's Expand on Our Template
  • The setup() Method
  • Event Handlers
  • Putting It Together: Build a Calculator
  • Method Summary
  • Definitions

    Introduction

    This tutorial assumes that you have read and completed the following two tutorials.

    1. Your First Cup of Java
    2. Getting Started
    3. Tutorial: A Second Cup of Java
    4. A basic Calculator using Swing .
    The rest of this tutorial will build on and reinforce what you learned from the above tutorials. This tutorial will expand on:
    1. JButton
    2. JPanel
    3. JTextField
    4. Container
    5. String

    In addition, this tutorial assumes that you understand templates. In this tutorial we will build on the basic four-function calculator. The calculator that we build will look like:

    Figure 1: Basic Calculator


    Requirements

    The requirements for the task are:

    1. Build a calculator application, using the application template.
    2. Build a four function calculator with the following functions:
      • Addition - adds two numbers: n1 + n2.
      • Subtraction - subtracts number two from number one: n1 - n2.
      • Multiplication - Multiplies two numbers: n1 * n2.
      • Division - divides number two into number one: n1 / n2.
      • Provide minimal error checking, in order to keep the code less complex.
    3. Use JButton for the numbers, functions, Exit, Help, and About.
    4. Create a class to respond to the events caused by the numbers, functions, Exit, Help, and About buttons.

    Requirements for Basic Calculator II

    1. +/- button: negates the sign of x.
    2. Pow button: raises the value x to the power of y: xy.
    3. 1/x button: divides the value of x into one.
    4. Sqrt button: calculates the square root of the value of x.
    5. CE button: clears the current value in the entry box.
    6. CA button: clears all values (i.e., pending operations, and values except those in the M+ queue).
    7. M+ button: loads values into a LIFO queue.
    8. M- button: pops values from a LIFO queue.
    9. n! button: calculates the factorial value of the number in the entry box.
    In the next section, we will explore Holland's OOP Programming Design Model.

    What is the Holland's OOP Programming Design Model?

    In object-oriented programming, programming revolves around the data. So in this style, the top is the data. It might be depicted as follows:

      
              +--------------+
              |      Data    |<----+  
              +-------+------+     | 
                      ^            |
                      |----------->+
                      V            ^
              +-------+------+     |
              |   Top-down   |     | 
              |  Structured  |<----+
              |  programming |     |
              |  on Classes  |     | (step-wise)
              |  and methods |     | (refinement)
              +--------------+     | (as needed) 
                      |            |
                      +------------+ 
     
      
    Figure 2: Holland's OOP Programming Design Model


    The data is entered in the Display box (JTextField) on the calculator, using the pushbuttons with numbers and/or a dot on it. This data is operated on in a binary (two numbers) fashion or in a unary (one number) fashion. The calculator operates in a

    1. binary (two numbers)
      • Multiplication
      • Division
      • Subtraction
      • Addition
    2. unary (one number) fashion
      • Plus/Minus
    3. Application functions
      • Clear
      • Clear Entry
      • Exit
    4. Equals sign displays the result of binary and/or unary operations.
    5. The pressing of the pushbuttons will result in an event handler (method) responding to the event.
      • Button Clear Entry Pressed
      • Button Clear Pressed
      • Button Plus Pressed
      • Button Minus Pressed
      • Button Multiplication Pressed
      • Button Division Pressed
      • Button Exit Pressed
      • Button Help Pressed
      • Button About Pressed
    In the next section, I will describe how to build the calculator template.

    Application Template

    We are going modify the template used in the Second Cup of Coffee by having it extend the JFrame class.

      
    /** 
     * The MyCalc class implements an application 
     * and extends JFrame.
     */
    class MyCalc extends JFrame {
    
        /** BasicCalc_II constructor */
        public MyCalc_II() {
           initialization code
           ...
        } 
    
        public static void main(String[] args) {
            /** creates an instance of BasicCalc  */
            MyCalc app = new MyCalc() ; 
        }
    }
      
    Figure 3: MyCalc class template


    Let's consider the class of automobile, which contains the set of all automobiles. A sampling might be:

    • Acura TL
    • BMW 5 series
    • Buick Century
    • Ford Explorer
    • Honda Pilot
    • Mazda6
    • Toyota Avalon
    • Toyota Highlander
    • Volvo S60
    • etc.
    If we were to write one of the examples above in Java, it might look like:

      
    
    class Toyota extends automobile {
       ...
    }
    
    class Avalon extends Toyota {
       ...
    }
      
    Figure 4: Automobile Template


    This example is interpreted as class Avalon inherits from class Toyota and class Toyota inherits from class automobile. In the case of our calculator,

      
    
    class BasicCalc extends JFrame {
       ...
    }
      
    Figure 5: Basic Calculator class


    BasicCalc inherits from JFrame. A more detailed discussion of inheritance is beyond the scope of this tutorial. You can find a write-up on inheritance at sun.com.

    Let's Expand on Our Template

    In many textbooks, these beginning sections start off with much of the initialization taking place in the main() method. In reality, much of the initialization takes place in a piece of code called a constructor. A constructor is a method that has the same name as the class. At this point our application template looks like:

      
      
    /** 
     * The MyCalc class implements an application 
     * and extends JFrame.
     */
    class MyCalc extends JFrame {
    
        /** MyCalc constructor */
        public MyCalc() {
             //initialization code
    
          super( "Simple Calculator" );
          setup() ;
                /** sets the size of the frame */
          setSize( 350, 300 );  
                /** sets the location of the frame on the screen*/
          setLocation( 200, 200 ) ; 
                /** makes the frame visible */    
          show();                  
        } 
    
        public static void main(String[] args) {
               /** creates an instance of BasicCalc  */
            MyCalc app = new MyCalc() ;
        }
    }  
      
    Figure 6: Basic Calculator class Template


    where the method setup() has the majority of the initialization code. A line of interest is the following:

      
    super( "Simple Calculator" );
    
      
    Figure 7: Calculator Title


    This line is a call to the parent class' constructor. In this case, it is a call to JFrame's constructor with the title for the frame.

    The setup() Method

    When we are considering adding graphics to a frame, we need an anchor (context) that we can use as a reference for all of the graphics. The display area for a JFrame has a context, called a content pane to which the graphics must be attached if they are to be displayed at run time. To get the context in Java, we write a line similar to:

      
    Container c = getContentPane(); // get the context or content pane
      

    We are at a design point. We need to lay out the graphics in a precise order. Specifically, we need to have

    • One graphic at the top (North);
    • Four rows in the middle, with each containing three graphics (Center);
    • One row at the bottom containing three graphics (South);
    • Four rows on the right, with each containing one graphic (East);
    With this lay out, our grouping would look like:

    Figure 8: The Layout for the Various Areas

    In Figure 8, 1x3 means that there is one row with three graphics in that row. We will use a Layout Manager to group our graphics. However, there is a problem. We can have only one Layout Manager per Container. How do we solve this problem? A Container can contain other Containers. Complex GUIs that require that each component be placed in an exact location usually consist of multiple containers called JPanels.

    We will use two different Layout Managers to accomplish our goals. We will use the BorderLayout Manager to place the JPanels in the appropriate areas and the GridLayout Manager for rows and columns. For example, to create a JTextField and a JPanel and then add them to the Container c follows.

      
              // adds the JTextField to the textPanel
    JTextField enterBox  = new JTextField( 15 ) ;
              // adds the textPanel to
    JPanel textPanel = new JPanel() ;
    textPanel.add(enterBox ) ;   
             // adds the textPanel to
             // the Container c North part
    c.add( textPanel , BorderLayout.NORTH ) ; 
      
    Figure 9: Add JTextField and textPanel


    A code snippet showing how to use the GridLayout Manager follows.

      
    buttonPanel = new JPanel() ;
    c.add( buttonPanel , BorderLayout.CENTER ) ;
    
    JButton bZero   = new JButton( "0" ) ;
    
    buttonPanel.add( bZero ) ;
    
    buttonPanel.setLayout( new GridLayout( 5, 3, 5, 5  ) );
    
      
    Figure 10: Using GridLayout Manager


    We can use these code examples to layout the face of the calculator. Next we need to write the code that responds to a button being pressed.

    Event Handlers

    When a button is pressed, it is called and event. The code that responds to this event is called an event handler. In the event handler, there is code to perform the appropriate task in response to the event. For example, suppose the zero button is pressed. The following code is an example of what happens.

      
    public void actionPerformed( ActionEvent e )    {
       if ( e.getSource() == bZero ) {
          enterBox.setText( enterBox.getText() + "0" ) ;
       }
    }
      
    Figure 11: Event Handler


    Putting It Together: Build a Calculator

    The structure for our calculator looks something like this:

      
    
    MyCalc
    +----------------------------------+
    |                                  |
    |  +----------------------+        |
    |  | actionPerformed()    |        |
    |  +----------------------+        |
    |  | MyCalc()             |        |
    |  +----------------------+        |
    |  | ConvertNumsToDouble()|        |     
    |  +----------------------+        |
    |  | divOp()              |        |     
    |  +----------------------+        | 
    |  | main()               |        |     
    |  +----------------------+        |
    |  | multOp()             |        |     
    |  +----------------------+        |
    |  | MyEqual()            |        |     
    |  +----------------------+        |
    |  | MyFact()             |        |     
    |  +----------------------+        |
    |  | MyMinus()            |        |     
    |  +----------------------+        |  
    |  | MyPrint( )           |        |     
    |  +----------------------+        |  
    |  | MySqrt()             |        |     
    |  +----------------------+        |
    |  | OneDivX()            |        |     
    |  +----------------------+        | 
    |  | opCodeMethod()       |        |     
    |  +----------------------+        |
    |  | PlusMinus()          |        | 
    |  +----------------------+        |
    |  | powerOp()            |        |    
    |  +----------------------+        |  
    |  | setResults()         |        |     
    |  +----------------------+        |
    |  | setUpActionListener()|        |
    |  +----------------------+        | 
    |  | setUpButtons()       |        |
    |  +----------------------+        |
    |  | setUpExitPanel()     |        |
    |  +----------------------+        | 
    |  | setUpFunctionPanel() |        |
    |  +----------------------+        | 
    |  | setup()              |        |     
    |  +----------------------+        |
    |  | subOp()              |        |     
    |  +----------------------+        |
    |  | sysExit()            |        |     
    |  +----------------------+        |
    |                                  |  
    +----------------------------------+
    
    
      
    Figure 12: Putting It Together: Build a Calculator


    • MyCalc() - constructor used for initialization
    • main() - entry point for the application at run time
    • actionPerformed() - This is the method that is called to respond to an event
    • checkFirstNum() - checks for a number and ensures that it is not null
    • ConvertNumsToDouble() - converts numbers entered from string to double
    • divOp() - divides the two entered numbers and checks for a zero divisor
    • multOp() - multiplies the two entered numbers
    • MyPrint( ) - toggles debug aid on or off
    • MySqrt() - computes the square root of the entered number
    • OneDivX() - computes the value of one divided by the entered number
    • opCodeMethod() - determines if there is a pending op to perform
      • if so, that operation is performed
      • if not, the current operation is performed
    • PlusMinus() - toggles the sign of the entered number
    • plusOp() - adds the two entered numbers
    • powerOp() - raises the first number to the power of the second e.g., n1n2
    • setResults() - enters the result of an operation in the textbox and the firstNum
    • setup() - The setup() method is used to allocate the panel and button objects using the new function.
    • subOp() - subtracts the second number from the first number
    • sysExit() - causes the application to exit

    Method Summary

    The following table shows the method summary. .
    BasicCalc_II Method Summary
    Method Name Description
    actionPerformed() The actionPerformed() method is the method that is called to respond to a button event.
    convertNumsToDouble() converts numbers entered from string to double data type.
    divOp() divides the two entered numbers and checks for a zero divisor
    1. If the pending operation Code equals 1 then
      1. Get the second number
      2. Convert the numbers to double
      3. If the first number is zero, then the answer is zero
      4. If the second number is zero, then indicate that dividing by zero is not allowed
      5. Otherwise, multiply the numbers
      6. Indicate there are no pending operations
      7. Call setResults()
    2. Check for pending operations other than divide
    3. It must be divide operation, so get the first number
    main(String[] args) The main() method is the entry point called by Java when this application is loaded.
    MyEqual() sets the entry box to the results of any pending operation.
    MyFact() computes the factorial of the entered number. For example, 5! = 5*4*3*2*1 = 120 The logic is:
    1. If there is a pending operation, proces it.
    2. Take the squareroot of the value in the enter box field.
    3. Store the anser into firstNum and dNum1
    4. Set the secondNum to null
    5. Enter firstNum/answer into the enter box field
    6. Set dNum2 to 0.0
    7. Indicate that there are no pending oprations.
    MyMinus The MyMinus()) method retrieves a number from the meory. The logic is:
    1. If there are numbers to be retrieved
      1. Retrieve a number using LIFO.
      2. Decrement the array index.
      3. If there is a pending operation:
        1. Store the number in the entry box into the second number and indicate that the second number has been set.
        2. Call the opCodeMethod() method.
      4. If there is a pending operation, indicate that the first number has been set.
    2. If there are no numbers in the array to retriev, indicate to the user that there are no numbers.
    MyPrint() toggles debug aid on or off.
    MySqrt() computes the square root of the entered number. The logic is:
    1. If there is a pending operation, proces it.
    2. Take the squareroot of the value in the enter box field.
    3. Store the anser into firstNum and dNum1
    4. Set the secondNum to null
    5. Enter firstNum/answer into the enter box field
    6. Set dNum2 to 0.0
    7. Indicate that there are no pending oprations.
    multOp() multOp() method multiplies two numbers. he logic is:
    1. If the pending operation Code equals 0 then
      1. Get the second number
      2. Convert the numbers to double
      3. Multiply the numbers
      4. Indicate there are no pending operations
      5. Call setResults()
    2. Check for pending operations other than multiplication
    3. It must be multiplication operation, so get the first number
    OneDivX() computes the value of one divided by the entered number. The logic is:
    1. If there is a pending operation, proces it.
    2. Divide the answer/result into 1.0.
    3. Store the anser into firstNum and dNum1
    4. Set the secondNum to null
    5. Enter firstNum/answer into the enter box field
    6. Set dNum2 to 0.0
    7. Indicate that there are no pending oprations.
    opCodeMethod() determines if there is a pending op to perform - if so, that operation is performed - if not, the current operation is performed
    PlusMinus() toggles the sign of the entered number
    plusOp() adds the two entered numbers. The logic is:
    1. If the pending operation Code equals 3 then
      1. Get the second number
      2. Convert the numbers to double
      3. Add the second number from the first number
      4. Indicate there are no pending operations
      5. Call setResults()
    2. Check for pending operations other than addition
    3. It must be addition operation, so get the first number
    powerOp() raises the first number to the power of the second. For example,
    5 Pow 2 = 25
    setResults() enters the result of an operation
    1. In the textbox, firstNum and dNum1
    2. Sets the indicator that the first number is set
    3. Sets the indicator that a result has been reached
    4. Indicates that there is no operation pending.
    setup() The setup() method is used to allocate the panel and button objects using the new function.
    1. Instantiate a JTextField object
      1. Initiate the textfield with a "0"
      2. Insure that the textfield is not editable
      3. Set the textfield background color to "white"
      4. Set the textfield Horizontal alignment to "right"
      5. All an event listner to the textfield
    2. Add an JPanel
    3. Add the JTextField to the JPanel
    4. Add the JPanel to the North section
    5. Call setUpButtons() to create the JButtons
    6. Call etUpActionListener() method to set up the event * listner responses
    7. Add the buttons to the buttonPanel
    8. Call setUpFunctionPanel()
    9. Call setUpExitPanel()
    setUpActionListener() The setUpActionListener() method assigns an event handler to the button and indicate that the responses will be handled inside the BasicCalc class,
    setUpButtons() The setUpButtons() method creates and initializes the buttons for this application. The logic is:
    1. Create the 0 - 9, +, -, /, *, Exit, POW, SQRT, and decimal buttons.
    2. Set the font type and size of the font for some of the buttons.
    setUpExitPanel() The setUpExitPanel() method creates and sets up the background color the foreground text for the buttons. The logic:
    1. Create the exit panel.
    2. Add the exitPanel to South border location.
    3. Create the Exit, Help, About button.
    4. Create the background and foreground colors for the above buttons.
    5. Create the fonts and size of these fonts for the above buttons.
    6. Add the above buttons to the exit panels.
    7. Add the above buttons to this class' action listner.
    setUpFunctionPanel() The setUpFunctionPanel() method creates the function panel and adds its buttons. The logic:
    1. Create the function panel and add it to the East border location.
    2. Create the Clear Entry, Clear All, M+ (Add to memory), M- (retrieve from memory), and !n (factorial buttons
    3. Add the above buttons to the function Panel.
    4. Add background and foregruond colors to the above buttons.
    5. Add the above buttons to this class' action listner.
    subOp() subtracts the second number from the first number The logic is:
    1. If the pending operation Code equals 2 then
      1. Get the second number
      2. Convert the numbers to double
      3. Subtract the second number from the first number
      4. Indicate there are no pending operations
      5. Call setResults()
    2. Check for pending operations other than subtraction
    3. It must be subtraction operation, so get the first number
    setUpTextField() The setUpTextField() method creates the test field that displays the numbers entered and the results of mathematical operations.
    sysExit() causes the application to exit

    Definitions

    BorderLayout - A border layout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center.

    extends - when considering class MyClass extends ParentClass, MyClass inherits from ParentClass. Java does not support multiple inheritance; it supports only single inheritance.

    Container - A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components.

    GridLayout - Creates a grid layout with a default of one column per component, in a single row.

    JFrame - A JFrame is a top-level window with a title and a border.

    JPanel - is a generic lightweight container.

    Layout Manager - Defines the interface for classes that know how to layout objects in Containers.

    Template - is a unique class or pattern that can be used to build other software code.






  • HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript ]
    © 2002 - 2016 All Rights Reserved Total Application Works