Tutorial: A Second Cup of Java

Author: Ronald S. Holland
at
Total Application Works




To visit my site

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


To contact us

© 2002 - 2017 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)
  • <html>
    <head>
    <title>Example of a link </title>
    </head>
    <body>
    <a href="http://sumtotalz.com/TotalAppsWorks/SecondCupOfJava.html">
    Second cup of Coffee </a>
    </table>
    </body>
    </html>
    Download source
    Screenshot
    Coments
    1. 12/7/2004 5:58:32 PM: clifford edward burns
        why would you post something like this
    2. 12/12/2004 6:57:29 AM: Ronald Holland
        Mr. Burns,
        What type of examples would you be interested in seeing posted?
    3. 11/1/2005 3:15:44 PM: Yash
        This is good for beginner.
    4. 12/25/2008 12:45:51 PM: Raju Rajan
        great tutorial.


Read me first

The SCOC.zip file contains the following files:

  1. CompileRun_MyApp.bat - this file compiles and runs the main program (MyApp.java). Double click on this filename in the directory to run.
    • MyApp.java - source file
  2. CompileRun_MyApp1.bat - this file compiles and runs the main program (MyApp1.java). Double click on this filename in the directory to run.
    • MyApp1.java - source file
  3. CompileRun_Myapplet1.bat - this file compiles and runs the main program (Myapplet1.java). Double click on this filename in the directory to run.
    • Myapplet1.java - source file
  4. CompileRun_MyAppTemplate_1.bat - this file compiles and runs the main program (MyAppTemplate_1.java). Double click on this filename in the directory to run.
    • MyAppTemplate_1.java - source file
  5. CompileRun_MyCalc.bat - this file compiles and runs the main program MyCalc.java). Double click on this filename in the directory to run.
    • MyCalc.java - source file
  6. CompileRun_MyCalc1.bat - this file compiles and runs the main program (MyCalc1.java). Double click on this filename in the directory to run.
    • (MyCalc1.java - source file
  7. CompileRun_MyCalcApp.bat - this file compiles and runs the main program (MyCalcApp.java). Double click on this filename in the directory to run.
    • MyCalcApp.java - source file
  8. SecondCupOfJava.html - is the tutorial that describes how to build all of the above programs

Introduction

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

  1. Your First Cup of Java
  2. Getting Started
This tutorial is intended to help you get started with Java. It is intended for the inexperienced programmer. The rest of this tutorial will build on and reinforce what you learned from The First Cup of Java tutorial. This tutorial will expand on:
  1. What is a class?
  2. The Hello World application.
  3. The Hello World applet.

We will discuss the term template as we ease into this tutorial as we build the following:
  1. MyApp - shows how to build a simple Hello application that gets the user's name.
  2. MyApp1 - builds an application that shows how to add, multiply and find the average of three numbers entered by the user.
  3. MyApplet - builds an applet that shows how to add, multiply and find the average of three numbers entered by the user.
  4. MyApplet1 - shows how to build a simple Hello applet that gets the user's name.
  5. MyCalc - builds a four function calculator application with the following functions:
    • Addition
    • Subtraction
    • Multiplication
    • Division
  6. MyCalcApp - builds a four function calculator applet with the following functions:
    • Addition
    • Subtraction
    • Multiplication
    • Division
  7. MyCalc1 - builds on the four function calculator application with the following functions:
    • Addition
    • Subtraction
    • Multiplication
    • Division
    • Power
    • Change Sign
    • Inverse of number
    • Square Root
    • N factorial


top

If you do not have the Java documentation

If you do not have the Java Documentation installed, you can download a copy from:

  1. J2SE 1.3.1
  2. JavaTM 2 Platform, Standard Edition, v 1.4.2 API Specification
  3. JDKTM 5.0 Documentation
If you do not have a high speed Internet connection, you can use an Internet connection at a college or many libraries have these high speed connections. You can download to a flash drive or to an external disk drive.

How to Obtain Java

If you do not have the Java installed, you can download a copy from:

  1. J2SE 1.3.1
  2. Java(TM) 2 SDK, Standard Edition 1.4.2_08
  3. Java SE 5.0 Downloads

What is a Template?

If you look in a dictionary, template is defined as

    a pattern, usually in the form of a thin plate of metal, wood, plastic, etc., for forming an accurate copy of an object or shape

In C++, a template is a keyword that allows you to create generic functions and/or classes. Java has a keyword interface that is similar, but for our purposes, we will say they are not the same. Based on what we have seen in the tutorials Getting Started and First cup of Java, how does the term template apply? Remember that a template is a pattern; therefore, the application template for Hello World looks like:
Hello World Application/Applet
  
/** 
 * The HelloWorldApp class implements an application that
 * simply displays "Hello World!" to the standard output.
 */
class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); //Display the string.
    }
}
  
Below is the outline for an applet
  
import javax.swing.JApplet.*;
import java.awt.*;
 
/**
 * The HelloWorld class implements an applet that
 * simply displays "Hello World!".
 */
public class HelloWorld extends JApplet {
    public void paint(Graphics g) {
        // Display "Hello World!"
        g.drawString("Hello world!", 50, 25);
    }
}
  
Figure 1: Hello world as an Application and an Applet

What's Wrong with This Picture?

The problem is that a template is supposed to be a generic pattern and the two examples above are not generic. To make our application and applet generic, we will make some changes and so our templates in pseudocode format look like:
  
/** 
 * The MyApp class implements an application.
 */
class MyApp {
    public static void main(String[] args) {
        code
        ...
    }
}

  
and the template for the applet looks like:
  
import java.applet.*;
import java.awt.*;
 
/**
 * The MyApplet class implements an applet.
 */
public class MyApplet extends Applet {
    public void paint(Graphics g) {
        // Display "something!"
        g.drawString("something!", 50, 25);
    }
}
  
Figure 2: Pseudocoded Application and an Applet

The Templates Are Not Quite Generic Enough

In many text books, 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 names as the class. At this point our application template looks like:
  
/** 
 * The MyApp class implements an application.
 */
class MyApp {

    // MyApp constructor
    public MyApp() {
       initialization code
       ...
    } 

    public static void main(String[] args) {
        minimal code
        ...
    }
}
  
The applet API also has an initialization method
called init(). Therefore, our applet template would look like:
  
import javax.swing.JOptionPane ;
import javax.swing.* ;
import javax.swing.JApplet.* ;
import java.awt.Graphics ;
 
/**
 * The MyApplet class implements an applet.
 */
public class MyApplet extends JApplet {

    public void init() {
        // initialization code
        initialization code...
        ...
    }

    public void paint(Graphics g) {
        // Display "something!"
        g.drawString("something!", 50, 25);
    }
}
  
Figure 3: Generic Application and an Applet Templates


A template allows us to create generic patterns. If we want a blueprint for something more specific, then we would consider a class.


top

What is a Class?

The dictionary defines a class as

    a number of people or things grouped together because of certain likenesses or common traits; kind; sort; category
The class of automobiles contains:
  • Acura TL
  • BMW 5 series
  • Buick Century
  • Ford Explorer
  • Honda Pilot
  • Mazda6
  • Toyota Avalon
  • Toyota Highlander
  • Volvo S60
  • etc.
When you buy a car, you get an instance of a brand and a model e.g., Toyota Highlander. We will modify the MyApp so we can get instances. This is done with the following line of code:
  

MyApp app = new MyApp() ; 

and the template looks like:

/** 
 * The MyApp class implements an application.
 */
class MyApp {

    /** MyApp constructor */
    public MyApp() {
       initialization code
       ...
    } 

    public static void main(String[] args) {
        MyApp app = new MyApp() ; /** creates an instance of MyApp  */
    }
}
 
(a working example can be found here.)
 
Figure 4: MyApp Template Application


Now that we have a template, we need a way to merge the template and the requirements. Assume that we have ten requirements, then using pseudocode, we can change the template in Figure 4 so that it now looks like:

  

MyApp app = new MyApp() ; 

and the template looks like:

/** 
 * The MyApp class implements an application.
 */
class MyApp {

    /** MyApp constructor */
    public MyApp() {
       initialization code
       ...
    } 

    /** req1_Method - this method implements requirement 1 */
    public req1_Method() {
       requirement 1 code
       ...
    } 

    /** req2_Method - this method implements requirement 2 */
    public req2_Method() {
       requirement 2 code
       ...
    } 

    /** req1_Method - this method implements requirement 3 */
    public req3_Method() {
       requirement 3 code
       ...
    } 

    ...

    /** req10_Method - this method implements requirement 10 */
    public req10_Method() {
       requirement 10 code
       ...
    } 
    public static void main(String[] args) {
        MyApp app = new MyApp() ; /** creates an instance of MyApp  */
    }
}
 
 
Figure 4a: MyApp Template with requirement pseudocode


We need a more formal description of what I did in Figure 4a. We will explore a more formal way to merge the template concept and the requirements in the next section. We will call this procedure, "Holland's OOP Programming Design Model."


top

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:

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


The data is entered in the Display box on the calculator, using the JOptionPanes to get the numbers from the user. This data is operated on in a binary (two numbers) fashion. The calculator operates in a

  1. binary (two numbers) fashion
    • Multiplication
    • Division
    • Subtraction
    • Addition
In the section on Putting It Together: Build a Calculator, I will describe how to build the calculator template.

Putting It Together: Build an Application I

Using the application template, build an application that:

  1. Asks the user for their name.
  2. Use JOptionPane to ask the user for their name.
    • JOptionPane - makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something.
    •  
      showInputDialog(Component parentComponent,
                      Object message,
                      String title,
                      int messageType)
       

      Where showInputDialog shows a dialog requesting input from the user parented to parentComponent with the dialog having the title and message type messageType.
    • Parameters:
      • parentComponent - the parent Component for the dialog
      • message - the Object to display
      • title - the String to display in the dialog title barmessage
      • Type - the type of message that is to be displayed:
        • ERROR_MESSAGE,
        • INFORMATION_MESSAGE,
        • WARNING_MESSAGE,
        • QUESTION_MESSAGE, or
        • PLAIN_MESSAGE.
  3. Writes "Hello username" to the screen.
    •  showMessageDialog(Component parentComponent,
                         Object message,
                         String title,
                         int messageType)
       

  4. Writes "My name is TAW" to the screen.
  5. The solution follows. Due to the simplicity of this example, we will not demonstrate how to use Holland's OOP Programming Design Model here.
    
/**
 * The MyApp class implements an application.
 */

import javax.swing.JOptionPane ;

class MyApp {

   String name ;     // name of user
 
   /** MyApp1 constructor */
   public MyApp() {
      /** read in the name of the user as a string */
      name =
         JOptionPane.showInputDialog( "Please enter your name." );

      JOptionPane.showMessageDialog(
         null,
         "Hello " + name,
         "Hello",
         JOptionPane.PLAIN_MESSAGE );

      JOptionPane.showMessageDialog(
         null,
         "My name is TAW",
         "My name",
         JOptionPane.PLAIN_MESSAGE );
   } 

   public static void main( String args[] ) {

      MyApp app = new MyApp() ; /** creates an instance of MyApp  */

      System.exit( 0 );   /** end the program */
   }
}
  
Figure 5: MyApp Application


top

Putting It Together: Build an Applet I

Using the applet template, build an applet that:

  1. Extends JApplet.
  2. Asks the user for their name.
  3. Use JOptionPane to ask the user for their name.
  4. Writes "Hello username" to the screen.
  5. Writes "My name is TAW" to the screen.
  6. The solution follows.
  
/** ***************************************************
 * File:  The MyApplet class implements an applet. 
 */

import javax.swing.JOptionPane ;
import javax.swing.* ;
import java.awt.Graphics ;

public class MyApplet extends JApplet {

   String name;     // name of user
           
        

    /** MyApp init() */
   public void init() {
      
      name =
         JOptionPane.showInputDialog( "Enter your name" );
   }

   public void paint( Graphics g) {
      /** show the results */
      g.drawRect( 15, 20, 200, 105 ) ;
      g.drawString( "Hello " + name, 25, 45 ) ;
      g.drawString( "My name is TAW ", 25, 75 ) ;

   }
}
  

Figure 6: MyApplet Applet


top

Putting It Together: Build an Application II

Build an application using the application template that:

  1. Requests three floating point numbers from the user.
    • Use JOptionPane class to request the user input.
  2. Adds these numbers together.
  3. Multiplies the three numbers e.g., prod = num1 * num2 * num3
  4. Determines the average of these three numbers.
  5. The solution follows:
  


/** ************************************************************* 
 * The MyApp1 class implements an application that:
 * 1- Requests three numbers from the user and then:
 * 2 - Determines the sum of three numbers
 * 3 - Determines the product of three numbers
 * 4 - Determines the average of three numbers
 * 5 - Displays the above results on the user's screen
 *  
 *****************************************************************/

import javax.swing.JOptionPane ;

class MyApp1 {

   String firstNum,     // first string entered by user
           secondNum,    // second string entered by user
           thirdNum;     // second string entered by user
   double num1,         // first number to add
        num2,            // second number to add
        num3,            // second number to add
        sum,             // sum of num1, num2 and num3
        prod,            // prod of num1, num3 and number2
        avg;             // average of num1, num3 and number2

    /** MyApp constructor */
   public MyApp1() {
      getNumbers();
      convertNumbers();
      sumNumbers();
      prodNumbers();
      avgNumbers();
      outputNumbers();
   }

   /** *************************************************** 
   * getNumbers() - requests and obtains three number from
   * the user.
   *****************************************************/
   public void getNumbers() {
      /** read in first number from user as a string */
      firstNum =
         JOptionPane.showInputDialog( "Enter first integer" );

      /** read in second number from user as a string */
      secondNum =
         JOptionPane.showInputDialog( "Enter second integer" );

      /** read in third number from user as a string */
      thirdNum =
         JOptionPane.showInputDialog( "Enter third integer" );
   }

   /** *************************************************** 
   * convertNumbers() - converts numbers from type String 
   * to type Double 
   *****************************************************/
   public void convertNumbers() {
      num1 = Double.parseDouble( firstNum );
      num2 = Double.parseDouble( secondNum );
      num3 = Double.parseDouble( thirdNum );
   }

   /** ******************************************************* 
    * sumNumbers() - Determines the sum of the three numbers
    * obtained from the user. 
    ***********************************************************/
   public void sumNumbers() {
      /** add the numbers */
      sum = num1 + num2 + num3;
   }

   /** ************************************************************* 
    * prodNumbers() - Determines the product of the three numbers
    * obtained from the user. 
    *****************************************************************/
   public void prodNumbers() {
      /** add the numbers */
      prod = num1 * num2 * num3;
   }

   /** ************************************************************* 
    * prodNumbers() - Determines the average of the three numbers
    * obtained from the user. 
    *****************************************************************/
   public void avgNumbers() {
      /** add the numbers */
      avg = ( num1 + num2 + num3 ) / 3;
   }

   /** **************************************************** 
    * outputNumbers() - displays the sum, product, and the 
    * average of the three numbers obtained from the user.
    ******************************************************/
   public void outputNumbers() {
      /** display the results */
      JOptionPane.showMessageDialog(
         null,
         "The sum is " + sum + "\n" +
         "The product is " + prod + "\n" +
         "The average is " + avg,
         "Results",
         JOptionPane.PLAIN_MESSAGE );
   }

   /** *************************************************** 
    * main() - This is the entry point that Java calls 
    * when the program is loaded into memory.
    *******************************************************/
   public static void main( String args[] ) {

      MyApp1 app = new MyApp1() ; /** creates an instance of MyApp  */

      System.exit( 0 );   /** end the program */
   }
}

  
Figure 7: MyApp1 Application Code Example


top

Putting It Together: Build an Applet II

Build an application using the application template that:

  1. Requests three floating point numbers from the user.
    • Use JOptionPane class to request the user input.
  2. Adds these numbers together.
  3. Multiplies the three numbers e.g., prod = num1 * num2 * num3
  4. Determines the average of these three numbers.
  5. The solution follows:
  

import javax.swing.JOptionPane ;
import javax.swing.* ;
import java.awt.Graphics ;

/** ************************************************************* 
 * The MyApplet1 class implements an applet that:
 * 1- Requests three numbers from the user and then:
 * 2 - Determines the sum of three numbers
 * 3 - Determines the product of three numbers
 * 4 - Determines the average of three numbers
 * 5 - Displays the above results on the user's screen
 *  
 *****************************************************************/
public class MyApplet1 extends JApplet {

   String firstNum,     // first string entered by user
           secondNum,    // second string entered by user
           thirdNum;     // second string entered by user
   double num1,         // first number to add
        num2,            // second number to add
        num3,            // second number to add
        sum,             // sum of num1, num2 and num3
        prod,            // prod of num1, num3 and number2
        avg;             // average of num1, num3 and number2

    /** MyApplet1 init() method */
   public void init() {
      getNumbers();
      convertNumbers();
      sumNumbers();
      prodNumbers();
      avgNumbers();
   }

   /** *************************************************** 
    * getNumbers() - requests and obtains three number from
    * the user.
    *****************************************************/
   public void getNumbers() {
      /** read in first number from user as a string */
      firstNum =
         JOptionPane.showInputDialog( "Enter first integer" );

      /** read in second number from user as a string */
      secondNum =
         JOptionPane.showInputDialog( "Enter second integer" );

      /** read in third number from user as a string */
      thirdNum =
         JOptionPane.showInputDialog( "Enter third integer" );
   }

  /** *************************************************** 
   * convertNumbers() - converts numbers from type String 
   * to type Double 
   *****************************************************/
   public void convertNumbers() {
      /** convert numbers from type String to type int */
      num1 = Double.parseDouble( firstNum );
      num2 = Double.parseDouble( secondNum );
      num3 = Double.parseDouble( thirdNum );
   }

   /** ******************************************************* 
    * sumNumbers() - Determines the sum of the three numbers
    * obtained from the user. 
    ***********************************************************/
   public void sumNumbers() {
      /** add the numbers */
      sum = num1 + num2 + num3;
   }

   /** ************************************************************* 
    * prodNumbers() - Determines the product of the three numbers
    * obtained from the user. 
    *****************************************************************/
   public void prodNumbers() {
      /** add the numbers */
      prod = num1 * num2 * num3;
   }

   /** ************************************************************* 
    * prodNumbers() - Determines the average of the three numbers
    * obtained from the user. 
    *****************************************************************/
   public void avgNumbers() {
      /** add the numbers */
      avg = ( num1 + num2 + num3 ) / 3;
   }

   /** ************************************************************* 
    * paint() - is an overwritten methos that writes the results on 
    * the reults on the screen. 
    *****************************************************************/
   public void paint( Graphics g) {
      /** show the results */
      g.drawRect( 15, 20, 200, 105 ) ;
      g.drawString( "The sum is " + sum, 25, 45 ) ;
      g.drawString( "The product is " + prod, 25, 75 ) ;
      g.drawString( "The average is " + avg, 25, 95 ) ;

   }


}

The HTML file needed is:

<html>
<applet code="MyApplet1.class" width=400 height=200>
</applet>
</html>

  
Figure 7: MyApp1 Application Code Example
If I enter the following numbers:
  1. 15.0
  2. 15.0
  3. 30.0
I get the following output:

The sum is 60.0

The product is 6750.0

The average is 20.0


top

Examples

  1. Template 1
     
    /** 
     * The MyAppTemplate_1 class implements an application.
     */
    class MyAppTemplate_1 {
    
        /** MyAppTemplate_1 constructor */
        public MyAppTemplate_1() {
           // initialization code
           // ...
           System.out.println("Currently in the constructor for MyAppTemplate_1.") ;
        } 
    
        public static void main(String[] args) {
                /** creates an instance of MyApp  */
            MyAppTemplate_1 app = new MyAppTemplate_1() ; 
        }
    }
    
     
    
    Figure 8: MyAppTemplate_1 Template

Putting It Together: Build a Calculator

In this section, we will learn how to build a very simple calculator. Using the application template, build an application that:

  1. Builds on the MyApp application. The MyApp application requirements are:
    • Gets three numbers from the user;
    • Adds the three numbers;
    • Multiplies the first number by the second number;
    • divides the first number by the second number;
  2. The calculator that we build should:
    • Gets two numbers from the user;
    • Adds the two numbers;
    • Multiplies the first number by the second number;
    • Divides the first number by the second number;
  3. The calculator that we build should create the following methods:
    • getNumbers() - Gets two numbers from the user; It calls
      • getFirstNumber() - gets the first number from the user
      • getSecondNumber() - gets the second number from the user
    • addNumbers() - Add two numbers;
    • subNumbers() - Subtract two numbers;
    • multNumbers() - Multiply two numbers;
    • divNumbers() - Divide two numbers;
    • showIn() - Shows a menu that allows the user to decide the operation to be performed;
    • checkIfDigit() - Ensure the data entered by the user are numbers;
      • JOptionPane - Alert the user when the data is not a number;
    • convertNumbers() - Convert the numbers from string values to type double;
    • Allow the user to cancel when entering data;
    • SysPrint() - Provide a debug mode.
We will show you how to use the Holland's OOP Programming Design Model in the next section.

How to use the Holland's OOP Programming Design Model

We will use Figure 4a above as our template.

  1. Substitute the method names in requirement number 3 for the method names in Figure 4a.
    • req1_Method becomes getNumbers().
    • Repeat until all of the methods in requirement 3 have been substituted into the Figure 4a template.
    • These methods will remain stubs until we do more step-wise refinement, based on our better understanding of the data.
  2. We will start defining our data, at this point.
    • The calculator that we build should get two numbers from the user.
    • The data will be stored in firstNumber and secondNumber.
    • The data entered on the JOptionPanes will be in String format.
    • Once the entered data is confirmed to be integers, convert them from String format to long format.
      • Store the firstNumber in num1, which is type double.
      • Store the secondNumber in num2, which is type double.
    • Declare the following variables type double:
      • sum - sum of num1 and num2
      • divi - contains the result of num1 divided by num2
      • prod - prod of num1 and num2
      • result - used to contain the result of an operation
    • Start using step-wise refinement to flesh out the logic in each method.
    • The MyCalc outline follows.



  
/** **************************************************************
 *  The MyCalc class is a four-function calculator.
 *****************************************************************/
class MyCalc {

   Declare variables
      ...

    /** MyCalc constructor */
   public MyCalc() {

   }

   /** **********************************************
    * Method: Menu()
    *
    * Purpose: displays the user options
    *   1 - Add two integers
    *   2 - Subtract two integers
    *   3 - Multiply two integers
    *   4 - Divide two integers
    *
    *   5 - Exit
    *
    *   The logic is:
    *   1 - Show the calculator menu options
    *   2 - Obtain the menu option chosen by the user
    *   3 - Validate the option number chosen by the user
    *   4 - Check to see if user has chosen to exit
    *       - if not, continue processing
    *   5 - Get the two user entered numbers
    *   6 - Perform the operation the user chose
    *   7 - Determine if the user wants to performed
    *       another operation
    *   8 - Determine if the user wants to use the
    *       result of the previous operation
    *
    ************************************************ */
   public void Menu() {

   }


   /** **********************************************
    * Method: getNumbers()
    *
    * Purpose: display JOptionpane to get user numbers
    *
    *   The logic is:
    *   1 - Use JOptionPane.showInputDialog to get 
    *       first number
    *   2 - If first number data ok, get second number
    *   3 - If second number data ok, convert numbers 
    *       to type long
    *
    ************************************************ */
   public boolean getNumbers() {

   }

  /** **************************************************
    *  Method: getFirstNumber()
    *    1- Determine if user wants to use result of 
    *       previous operation
    *    2- Get first number
    *    3- Alert user if first number is null
    *       Goto beginning of loop to get first number
    *       again
    *    4- Ensure number is a digit
    *    5- Alert user if first number is not a digit
    *    6- Break loop if user cancels  
    *    7- If user has chosen to use previous result, make 
    *       that result the first number    
    *
    ******************************************************/
   public int  getFirstNumber() {

   }

   /** **************************************************
    *  Method: getSecondNumber()
    *    1- Get second number
    *    2- Alert user if second number is null
    *       Goto beginning of loop to get second number
    *       again
    *    3- Ensure number is a digit
    *    4- Alert user if second number is not a digit
    *    5- Break loop if user cancels
    *
    ******************************************************/
   public int  getSecondNumber() {

   }


   /** **************************************************
    *  Method: checkDigit( String strVal )
    *    1- Make sure that the data entered is a digit
    *       - check each character to ensure it is a digit
    ******************************************************/
   public boolean  checkDigit( String strVal ) {

   }
   /** **************************************************
    *  Method: convertNumbers()
    *    1- Converts string data to type double.
    *
    ******************************************************/
   public void convertNumbers() {

   }

   /** **************************************************
    *  Method: convertNumbers()
    *    1- Converts string data to type double.
    *
    ******************************************************/
   public void SysPrint( String str ) {

   }

   /** **************************************************
    *  Method: addNumbers()
    *    1- Adds the first number to the second number.
    *
    ******************************************************/
   public void addNumbers() {

   }

   /** **************************************************
    *  Method: subNumbers()
    *    1- Subtracts the second number from the first number.
    *
    ******************************************************/
   public void subNumbers() {

   }

   /** **************************************************
    *  Method: multNumbers()
    *    1- Multiplies the first number by the second number.
    *
    ******************************************************/
   public void multNumbers() {

   }

   /** **************************************************
    *  Method: divNumbers()
    *    1- If the second number is 0.0, an alert is sent 
    *       to the user stating that division by zero is  
    *       not allowed.
    *    2- Divides second number into the first number.
    *
    ******************************************************/
   public void divNumbers() {

   }

   /** ***********************************************
    *  Method: showIn( String mess , String title )
    *    1- The purpose of this method is to display the
    *       menu using a JOptionPane - show calculator options.
    *
    **************************************************/
   public String showIn( String mess , String title ) {

   }

   /** ***********************************************
    *  Method: main( String args[] )
    *    1- The purpose of this method is to serve as a
    *       entry point when the application is loaded
    *       by Java.
    *    2- Creates an instance MyCalc class.
    *
    **************************************************/
   public static void main( String args[] ) {

   }
}
  
Figure 9: MyCalc Pseudocode

Putting It Together: Build a Calculator Applet

In this section, we will learn how to convert the very simple calculator we built above into an applet. Using the applet template, build an application that:

  1. Builds on the MyApplet applet in Figure 3. The MyApplet applet requirements are:
    • Gets three numbers from the user;
    • Adds the three numbers;
    • Multipliers the three numbers;
    • Averages the three numbers;
  2. The calculator that we build should create the following methods:
    • getNumbers() - Gets two numbers from the user; It calls
      • getFirstNumber() - gets the first number from the user
      • getSecondNumber() - gets the second number from the user
    • addNumbers() - Add two numbers;
    • subNumbers() - Subtract two numbers;
    • multNumbers() - Multiply two numbers;
    • divNumbers() - Divide two numbers;
    • showIn() - Shows a menu that allows the user to decide the operation to be performed;
    • checkIfDigit() - Ensure the data entered by the user are numbers;
      • JOptionPane - Alert the user when the data is not a number;
    • convertNumbers() - Convert the numbers from string values to type double;
    • Allow the user to cancel when entering data;
    • SysPrint() - Provide a debug mode.
  3. How to convert from an application to an applet follows:
    1. We start with MyApplet template in Figure 3 above.
    2. We change
       
      public class MyApplet extends Applet { 
      
      to 
      
      public class MyCalcApp extends JApplet {
       
    3. We change the init() method pseudocode from
       
      // initialization code
      initialization code...
       ...
      
      to
      
            menu  =         "                                         \n" ;
            menu  = menu  + "    Calculator Options                  \n" ;
            menu  = menu  + "                                         \n" ;
            menu  = menu  + "  1 - Add two integers                      \n" ;
            menu  = menu  + "  2 - Subtract an integer from an integer  \n" ;
            menu  = menu  + "  3 - Multiply two integers              \n" ;
            menu  = menu  + "  4 - Divide an integer into an integer  \n" ;
            menu  = menu  + "                                         \n" ;
            menu  = menu  + "  5 - Exit                               \n" ;
            menu  = menu  + "                                         \n" ;
            menu  = menu  + " Select one of the option numbers from above     \n" ;
      
            Menu();
       
    4. We include all of the MyCalc methods except the main() method. These methods are:
      1. init(): method used for any initialization
      2. Menu(): hub used to call
        • showIn()
        • checkIfDigit()
        • getNumbers()
        • addNumbers()
        • subNumbers()
        • multNumbers()
        • divNumbers()
      3. getNumbers(): calls
        • getFirstNumber()
        • getSecondNumber()
      4. addNumbers: adds two numbers
      5. subNumbers(): subtracts second number from first number
      6. multNumbers(): divides second number into first number
      7. getFirstNumber() - gets the first number from the user
      8. getSecondNumber() - gets the second number from the user
      9. checkIfDigit() - ensures the data entered by user is a digit
      10. convertNumbers() - convsrts data from string to type double
      11. showIn() - displays the menu
      12. SysPrint() displays debugging messages
      13. main() entry poing that Java calls upon loading program
The MyCalcApp outline follows.

  
/** **************************************************************
 *  The MyCalcAPP class is a four-function calculator.
 *****************************************************************/

import javax.swing.JOptionPane ;
import javax.swing.* ;
import javax.swing.JApplet.* ;
import java.awt.Graphics ;

class public MyCalcAPP extends JApplet{


    /** MyCalc init() method */
   public void init() {

   }

   /** **********************************************
    * Method: Menu()
    *
    * Purpose: displays the user options
    *   1 - Add two integers
    *   2 - Subtract two integers
    *   3 - Multiply two integers
    *   4 - Divide two integers
    *
    *   5 - Exit
    *
    *   The logic is:
    *   1 - Show the calculator menu options
    *   2 - Obtain the menu option chosen by the user
    *   3 - Validate the option number chosen by the user
    *   4 - Check to see if user has chosen to exit
    *       - if not, continue processing
    *   5 - Get the two user entered numbers
    *   6 - Perform the operation the user chose
    *   7 - Determine if the user wants to performed
    *       another operation
    *   8 - Determine if the user wants to use the
    *       result of the previous operation
    *
    ************************************************ */
   public void Menu() {

   }


   /** **********************************************
    * Method: getNumbers()
    *
    * Purpose: display JOptionpane to get user numbers
    *
    *   The logic is:
    *   1 - Use JOptionPane.showInputDialog to get 
    *       first number
    *   2 - If first number data ok, get second number
    *   3 - If second number data ok, convert numbers 
    *       to type long
    *
    ************************************************ */
   public boolean getNumbers() {

   }

  /** **************************************************
    *  Method: getFirstNumber()
    *    1- Determine if user wants to use result of 
    *       previous operation
    *    2- Get first number
    *    3- Alert user if first number is null
    *       Goto beginning of loop to get first number
    *       again
    *    4- Ensure number is a digit
    *    5- Alert user if first number is not a digit
    *    6- Break loop if user cancels  
    *    7- If user has chosen to use previous result, make 
    *       that result the first number    
    *
    ******************************************************/
   public int  getFirstNumber() {

   }

   /** **************************************************
    *  Method: getSecondNumber()
    *    1- Get second number
    *    2- Alert user if second number is null
    *       Goto beginning of loop to get second number
    *       again
    *    3- Ensure number is a digit
    *    4- Alert user if second number is not a digit
    *    5- Break loop if user cancels
    *
    ******************************************************/
   public int  getSecondNumber() {

   }


   /** **************************************************
    *  Method: checkDigit( String strVal )
    *    1- Make sure that the data entered is a digit
    *       - check each character to ensure it is a digit
    ******************************************************/
   public boolean  checkDigit( String strVal ) {

   }
   /** **************************************************
    *  Method: convertNumbers()
    *    1- Converts string data to type double.
    *
    ******************************************************/
   public void convertNumbers() {

   }

   /** **************************************************
    *  Method: convertNumbers()
    *    1- Converts string data to type double.
    *
    ******************************************************/
   public void SysPrint( String str ) {

   }

   /** **************************************************
    *  Method: addNumbers()
    *    1- Adds the first number to the second number.
    *
    ******************************************************/
   public void addNumbers() {

   }

   /** **************************************************
    *  Method: subNumbers()
    *    1- Subtracts the second number from the first number.
    *
    ******************************************************/
   public void subNumbers() {

   }

   /** **************************************************
    *  Method: multNumbers()
    *    1- Multiplies the first number by the second number.
    *
    ******************************************************/
   public void multNumbers() {

   }

   /** **************************************************
    *  Method: divNumbers()
    *    1- If the second number is 0.0, an alert is sent 
    *       to the user stating that division by zero is  
    *       not allowed.
    *    2- Divides second number into the first number.
    *
    ******************************************************/
   public void divNumbers() {

   }

   /** ***********************************************
    *  Method: showIn( String mess , String title )
    *    1- The purpose of this method is to display the
    *       menu using a JOptionPane - show calculator options.
    *
    **************************************************/
   public String showIn( String mess , String title ) {

   }
}
  
   
<html>
<applet code="MyCalcApp.class" width=400 height=200>
</applet>
</html>
 
Figure 10: MyCalcApp Applet Pseudocode

Putting It Together: Build an Advanced Calculator

In this section, we will learn how to add more functions to the previous simple calculator. Using the application template in Figure 9, build a calculator application that:

  1. Builds on the MyApp application. The MyApp application requirements are:
    • Gets three numbers from the user;
    • Adds the three numbers;
    • Multiplies the first number by the second number;
    • divides the first number by the second number;
  2. The calculator that we build should:
    • Gets two numbers from the user;
    • Adds the two numbers;
    • Multiplies the first number by the second number;
    • Divides the first number by the second number;
  3. The basic calculator that we build should create the following methods:
    • getNumbers() - Gets two numbers from the user; It calls
      • getFirstNumber() - gets the first number from the user
      • getSecondNumber() - gets the second number from the user
    • addNumbers() - Add two numbers;
    • subNumbers() - Subtract two numbers;
    • multNumbers() - Multiply two numbers;
    • divNumbers() - Divide two numbers;
    • showIn() - Shows a menu that allows the user to decide the operation to be performed;
    • checkIfDigit() - Ensure the data entered by the user are numbers;
      • JOptionPane - Alert the user when the data is not a number;
    • convertNumbers() - Convert the numbers from string values to type double;
    • Allow the user to cancel when entering data;
    • SysPrint() - Provide a debug mode.
  4. The added functions for the advanced calculator are:
    • Pow() - calculates the value of the first argument raised to the power of the second argument. the result is stored in the variable result.
    • changeSign() - this method changes the sign of the passed number.
    • invNumber() - divides a number into one to get the inverse of that number
    • sqrt() - Calculates the correctly rounded positive square root of a double value.
    • nFact() - Calculates the factorial of a number.
  • The MyCalc1 outline follows.



      
    /** **************************************************************
     *  The MyCalc class is a four-function calculator.
     *****************************************************************/
    class MyCalc {
    
       Declare variables
          ...
    
        /** MyCalc constructor */
       public MyCalc() {
    
       }
    
       /** **********************************************
        * Method: Menu()
        *
        * Purpose: displays the user options
        *   1 - Add two integers
        *   2 - Subtract two integers
        *   3 - Multiply two integers
        *   4 - Divide two integers
        *
        *   5 - Exit
        *
        *   The logic is:
        *   1 - Show the calculator menu options
        *   2 - Obtain the menu option chosen by the user
        *   3 - Validate the option number chosen by the user
        *   4 - Check to see if user has chosen to exit
        *       - if not, continue processing
        *   5 - Get the two user entered numbers
        *   6 - Perform the operation the user chose
        *   7 - Determine if the user wants to performed
        *       another operation
        *   8 - Determine if the user wants to use the
        *       result of the previous operation
        *
        ************************************************ */
       public void Menu() {
    
       }
    
    
       /** **********************************************
        * Method: getNumbers()
        *
        * Purpose: display JOptionpane to get user numbers
        *
        *   The logic is:
        *   1 - Use JOptionPane.showInputDialog to get 
        *       first number
        *   2 - If first number data ok, get second number
        *   3 - If second number data ok, convert numbers 
        *       to type long
        *
        ************************************************ */
       public boolean getNumbers() {
    
       }
    
      /** **************************************************
        *  Method: getFirstNumber()
        *    1- Determine if user wants to use result of 
        *       previous operation
        *    2- Get first number
        *    3- Alert user if first number is null
        *       Goto beginning of loop to get first number
        *       again
        *    4- Ensure number is a digit
        *    5- Alert user if first number is not a digit
        *    6- Break loop if user cancels  
        *    7- If user has chosen to use previous result, make 
        *       that result the first number    
        *
        ******************************************************/
       public int  getFirstNumber() {
    
       }
    
       /** **************************************************
        *  Method: getSecondNumber()
        *    1- Get second number
        *    2- Alert user if second number is null
        *       Goto beginning of loop to get second number
        *       again
        *    3- Ensure number is a digit
        *    4- Alert user if second number is not a digit
        *    5- Break loop if user cancels
        *
        ******************************************************/
       public int  getSecondNumber() {
    
       }
    
    
       /** **************************************************
        *  Method: checkDigit( String strVal )
        *    1- Make sure that the data entered is a digit
        *       - check each character to ensure it is a digit
        ******************************************************/
       public boolean  checkDigit( String strVal ) {
    
       }
       /** **************************************************
        *  Method: convertNumbers()
        *    1- Converts string data to type double.
        *
        ******************************************************/
       public void convertNumbers() {
    
       }
    
       /** **************************************************
        *  Method: convertNumbers()
        *    1- Converts string data to type double.
        *
        ******************************************************/
       public void SysPrint( String str ) {
    
       }
    
       /** **************************************************
        *  Method: addNumbers()
        *    1- Adds the first number to the second number.
        *
        ******************************************************/
       public void addNumbers() {
    
       }
    
       /** **************************************************
        *  Method: subNumbers()
        *    1- Subtracts the second number from the first number.
        *
        ******************************************************/
       public void subNumbers() {
    
       }
    
       /** **************************************************
        *  Method: multNumbers()
        *    1- Multiplies the first number by the second number.
        *
        ******************************************************/
       public void multNumbers() {
    
       }
    
       /** **************************************************
        *  Method: divNumbers()
        *    1- If the second number is 0.0, an alert is sent 
        *       to the user stating that division by zero is  
        *       not allowed.
        *    2- Divides second number into the first number.
        *
        ******************************************************/
       public void divNumbers() {
    
       }
    
    
    
       /** **************************************************
        *  Method: Pow() calculates the value of the first 
        *    argument raised to the power of the second 
        *    argument. the result is stored in the variable
        *    result.
        *
        ******************************************************/
        public void Pow() {
           
        }
    
       /** **************************************************
        *  Method: changeSign() - this method changes the sign   
        *          of the passed number.  
        *    
        ******************************************************/
        public void changeSign() {
          
        }
    
       /** **************************************************
        *  Method: invNumber() divides a number into one to 
        *          get the inverse of that number
        *
        ******************************************************/
        public void invNumber() {
            
        }
    
       /** **************************************************
        *  Method: sqrt() - Calculates the correctly rounded 
        *  positive square root of a double value.
        *
        ******************************************************/
        public void sqrt() { 
    
        }
    
       /** **************************************************
        *  Method: nFact() - Calculates the factorial of a
        *  number.
        *
        ******************************************************/
        public void nFact() { 
    
        }
    
       /** ***********************************************
        *  Method: showIn( String mess , String title )
        *    1- The purpose of this method is to display the
        *       menu using a JOptionPane - show calculator options.
        *
        **************************************************/
       public String showIn( String mess , String title ) {
    
       }
    
       /** ***********************************************
        *  Method: main( String args[] )
        *    1- The purpose of this method is to serve as a
        *       entry point when the application is loaded
        *       by Java.
        *    2- Creates an instance MyCalc class.
        *
        **************************************************/
       public static void main( String args[] ) {
    
       }
    }
      
    Figure 9: MyCalc Pseudocode




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

    © 2002 - 2017 All Rights Reserved Total Application Works