How to Develop a Simple Java Program
Last Revision: June, 2001
( McCann )

Students always seem to have trouble understanding (or maybe just doing) what I expect of them when I assign a program. The requirements are really very straight-forward; it's mostly a matter of leaving yourself plenty of time to get everything done.

To help you understand what's expected of you, in this document I'll take a simple sample programming assignment and guide you through the major steps in the program development process.

(If you are looking for details on program documentation, you will find some here but you really should visit my Programming Style page, which has my collection of style documents, including a few style pages from other people. Most of it is developed with experienced programmers in mind. This document is meant for students who are just starting to learn Java.)


Step #1: Start Early
Programming is not an activity that can be reliably scheduled to take a predetermined amount of time. Even programs that look like they should be doable in 2 hours will often take 4 or 5 hours to complete. The best thing you can do for yourself is say, "I have no idea how long this will take; I'd better get started right away."

Step #2: Read the Assignment Handout Carefully
My programming assignment handouts tend to be very detailed, if not perfectly organized. Everything that I expect from you is given in there somewhere, so read it carefully and highlight the key points so that you don't overlook any of them.

For example, let's consider this example assignment:




CS 001 -- Computer Science I

(McCann)

Program # -1: Calories Due to Fat

Due Date: Smarch 36th, 2028, at the beginning of class

Overview: Any dietician will tell you that limiting your daily fat intake to be under 30% of your total calories is a good idea. But how many of the calories in your favorite foods are from fat? Nutrition labels will tell you how many grams of fat are in a serving, and how many total calories are in that serving, but you need to do the rest of the figuring on your own.

As it happens, a gram of fat has about 9 calories. Therefore, if you take the grams of fat in a serving of a particular food, multiply it by 9 and divide by the total calories in the serving, you'll get the fraction of the calories due to fat. To get the result as a percentage, just multiply by 100.

For example, consider a product that has 3 grams of fat and 170 calories per serving. There are 27 calories due to fat (3 * 9), and 27 / 170 = 0.1588. Multiplying by 100 gives the final answer: 15.88 percent of the calories are due to fat.

Assignment: Write a complete, well-documented Java program that begins by asking the user to enter the grams of fat and the calories in a serving of a food product. The program will compute the percentage of the food's calories that are due to fat, and will display the input information and the percentage in the form of a complete English sentence.

Data: Run your program twice, once for each set of data shown in the following table:

 

Fat (grams)

Total Calories

1

1

66

2

21

480

Hand In: On the due date, turn in the following items: A printout of your documented Java program, and a printout of the output your program produced when run on each of the sets of data given above. Be sure to write your name in the upper right hand corner of the printout; this will make it easier for you to reclaim your program when I return it to you.




This is pretty typical of my program handouts. Things to notice: In this case, you need to write a program that gets two pieces of input, computes a percentage, and outputs all three pieces of information. This is obviously very simple, and the first program or two of the semester will be about as simple as this one. After that, they'll get more complex, so that you can start using more features of the language.

Step #3: Write the External Documentation
I can already hear the smirking ("Write comments now? Get serious!") but I am serious: You should write your documentation as you write the program, not afterwards. In particular, the External Documentation should be almost complete before you write even a line of code.

I hand out a one-page document (in PDF) to my programming classes that lists the information that I expect to see in your programs. In particular, here's what the External Documentation should contain:

  1. Your name, the course name/number, assignment name/number, instructor's name, and due date.
  2. Detailed description of the problem the program was written to solve, including the techniques (e.g., algorithms) used to solve the problem.
  3. The program's operational requirements: Which language system you used, special compilation information, where the input can be located on disk, etc.
  4. Required features of the assignment that you were not able to include, and/or information about bugs that are still known to exist. (Be honest and complete!)
To help you, I've created a template that you can import into your program that contains a label for each section that I want to see. All you have to do is fill in the blanks; I can't make it much easier than that. The Block Comment Templates with Examples page shows the External Documentation template, and you can find it in the directory /home/student/Classes/mccann/general/templates from the lab machines as well. You might wish to make copies of the templates in your home directory, just to make it easy to use your editor's file import command (:r in the vi editor, for example) to drop it into your program; importing the template can save a lot of typing.

Here's what the external documentation template (external.txt) looks like:

/*=============================================================================
 |   Assignment:  Program #[n]
 |       Author:  [Your Name (Your E-mail Address)]
 |
 |       Course:  [Course Number (Course Name), Semester and Year]
 |   Instructor:  L. McCann
 | Sect. Leader:  [Your Section Leader's name]
 |     Due Date:  [Due Date], at the beginning of class
 |
 |     Language:  [Program Language (Development Environment)]
 |     Packages:  [Names and Sources of any special code libraries used]
 |  Compile/Run:  [How to Compile and Run this program]
 |
 +-----------------------------------------------------------------------------
 |
 |  Description:  [Describe the program's goal, IN DETAIL.]
 |                
 |        Input:  [Describe the sources and formats of all user-supplied
 |                 input required by the program.]
 |
 |       Output:  [Describe the output that the user should expect the
 |                 program to produce.]
 |
 |   Techniques:  [Names of standard algorithms employed, explanations
 |                 of why things were done they way they were done, etc.
 |                 This is the place for technical information that another
 |                 programmer would like to know.]
 |
 |   Required Features Not Included:
 |                [If the assignment specifies a feature that you were
 |                 unable to include in the program, mention that omission
 |                 here.  Otherwise, state that you were able to include
 |                 all of the required features in your program.]
 |
 |   Known Bugs:  [If you know of any problems with the code, provide
 |                details here, otherwise clearly state that you know
 |                of know logic errors.]
 |
 *===========================================================================*/
Note that I've included some brief comments with each section, to let you know what you need to add. Because deleting all of those comments is a pain, I've got a comment-free version in the same directory called ext.txt that you can import instead.

You should be able to fill out all of this template except for the last two sections before you write the program. Here's what it might look like for our example assignment:

/*=============================================================================
 |   Assignment:  Program # -1
 |       Author:  Keyser Soze (keyser@onestepahead.net)
 |
 |       Course:  CS 001 (Computer Science I)
 |   Instructor:  L. McCann
 | Sect. Leader:  Wee Lufdaleeder
 |     Due Date:  Smarch 36, 2038, at the beginning of class
 |
 |     Language:  Java (JDK 1.3, BlueJ 1.1.0)
 |     Packages:  java.io
 |  Compile/Run:  BlueJ:  Compile: Create a project; add this class to
 |                                 it; click 'Compile'
 |                            Run: Right-click class icon; select
 |                                 'void main(args)'; click 'OK'
 |                  JDK:  Compile: javac Calories.java
 |                            Run: java Calories
 |
 +-----------------------------------------------------------------------------
 |  Description:  This program determines what percentage of the calories
 |                in a food product are due to the food's fat content.
 |
 |                The user is asked to input the number of grams of fat in one
 |                serving of the food, and the total calories in one serving.
 |                A gram of fat contains 9 calories, so the percentage of
 |                the food's calories that are due to fat is found by using
 |                this formula:
 |
 |                                # of grams of fat  *  9
 |                percentage = ----------------------------- * 100
 |                                calories in a serving
 |
 |        Input:  The user is required to enter the grams of fat in one
 |                serving of the food in question, and the total number of
 |                calories in that one serving.  It is expected that the
 |                user will type these two pieces of information at his or
 |                her keyboard.
 |
 |       Output:  The program will display an explanation of its purpose,
 |                will prompt the user for the input, and will display the
 |                percentage of the food's calories that are due to fat.  All
 |                output is displayed on the user's screen.
 |
 |   Techniques:  The program's steps are as follows:
 |
 |                      1.  The program displays its purpose
 |                      2.  The user is prompted to enter the grams of fat
 |                              and calories per serving
 |                      3.  The percentage of calories due to fat is
 |                              computed
 |                      4.  The percentage is displayed to the user, along
 |                              with the given input information.
 |
 |                No particular algorithms are used.  The Java IO package
 |                is accessed to perform console I/O and thus avoid use
 |                of a third-party I/O package.
 |
 |   Required Features Not Included:  All required features are included.
 |
 |   Known Bugs:  None; the program operates correctly.
 |
 *===========================================================================*/
Please pay attention to the amount of information; the explanations are all quite detailed. Many students try to include a bare minimum of information in their documentation; that's not good at all. The documentation should help the reader understand the program, not raise more questions than it answers. This example shows an adequate amount of information. (Can you think of some additional information that you'd like to see included?) Some students think that the reader can just refer to the assignment handout to get the information. Remember two things: First, the documentation is part of the program code; the handout isn't. Second, when you get a job as a programmer, your boss is not going to go around giving you assignment handouts. You might as well get in the habit of writing good, informative documentation now.

Naturally, the programmer will need to revisit the documentation after the program is complete and verify that all of the information is correct (and fill in the final two sections). But, if you do a good job of planning the details of the program in advance, you won't have to change much, if anything.

Step #4: Write the Program a Piece at a Time
Students like to try to write their programs all at once. You can get away with this on small programs, but as the amount of code increases, you're asking for headaches if you don't write a little at a time, and test each section as you write it.

For example, in our program we know that we need to read two pieces of data and output three, with some calculations in-between. Forget about the calculations for the moment, and just try to deal with the input and output. Your program might look like this: (I left off the external documentation in the interest of saving space.)

import java.io.*;          // For access to console I/O classes and methods

public class Calories
{
    public static void main (String[] args)
    {
        BufferedReader keyboard;    // input stream
        int    gramsOfFat = 0,      // number of grams of fat in one serving
               totalCalories = 0;   // number of calories in one serving
        double percent = 0;         // percentage of total calories from fat

        keyboard = new BufferedReader(new InputStreamReader(System.in));

        try {
            gramsOfFat = Integer.parseInt(keyboard.readLine());
        } catch (IOException e) {}

        try {
            totalCalories = Integer.parseInt(keyboard.readLine());
        } catch (IOException e) {}

        System.out.println(gramsOfFat + " " + totalCalories + " " + percent);
    }
}
Yes, this is very spartan. Don't worry, we'll fill in the details in due time. The point is, we can compile and run this program as-is, and be convinced that we are able to successfully read and write the data. It doesn't make much sense to write the percentage calculations until we know that the calculations will have the correct values to work with. By including a simple output statement, we can see that the values are being read correctly.

If you were to compile and run this program under Linux using the Sun JDK, here's what you'd see:

$ javac Calories.java
$ java Calories
3
170
3 170 0.0
Obviously, we'll need to make these input and output actions a lot more "user friendly" before we finish.

Next, we can add the calculations:

import java.io.*;          // For access to console I/O classes and methods

public class Calories
{
    public static final double CALORIES_PER_GRAM = 9.0;  // a gram of fat
                                                         // has 9 colories

    public static void main (String[] args)
    {
        BufferedReader keyboard;    // input stream
        int    gramsOfFat = 0,      // number of grams of fat in one serving
               totalCalories = 0;   // number of calories in one serving
        double fatFraction,         // fraction of calories due to fat
               percent;             // percentage of total calories from fat


        keyboard = new BufferedReader(new InputStreamReader(System.in));

        try {
            gramsOfFat = Integer.parseInt(keyboard.readLine());
        } catch (IOException e) {}

        try {
            totalCalories = Integer.parseInt(keyboard.readLine());
        } catch (IOException e) {}

        fatFraction = (gramsOfFat * CALORIES_PER_GRAM) / totalCalories;
        percent = fatFraction * 100;

        System.out.println(gramsOfFat + " " + totalCalories + " " + percent);
    }
}
Don't forget to test the calculations to ensure that they are working correctly. Remember the example calculation given in the assignment handout? It makes for a good test case:

$ javac Calories.java
$ java Calories
3
170
3 170 15.88235294117647
Eventually, you'll have added all of the functionality that is required of your program, will have tested its operation thoroughly, and will have added any remaining documentation. At this point, you may choose to add some "extras" that enhance the program but were not required by the assignment. (I never have problems when you do more than the assignment requires!) Here's what the completed program might look like:

/*=============================================================================
 |   Assignment:  Program # -1
 |       Author:  Keyser Soze (keyser@onestepahead.net)
 |
 |       Course:  CS 001 (Computer Science I)
 |   Instructor:  L. McCann
 | Sect. Leader:  Wee Lufdaleeder
 |     Due Date:  Smarch 36, 2038, at the beginning of class
 |
 |     Language:  Java (JDK 1.3, BlueJ 1.1.0)
 |     Packages:  java.io
 |  Compile/Run:  BlueJ:  Compile: Create a project; add this class to
 |                                 it; click 'Compile'
 |                            Run: Right-click class icon; select
 |                                 'void main(args)'; click 'OK'
 |                  JDK:  Compile: javac Calories.java
 |                            Run: java Calories
 |
 +-----------------------------------------------------------------------------
 |  Description:  This program determines what percentage of the calories
 |                in a food product are due to the food's fat content.
 |
 |                The user is asked to input the number of grams of fat in one
 |                serving of the food, and the total calories in one serving.
 |                A gram of fat contains 9 calories, so the percentage of
 |                the food's calories that are due to fat is found by using
 |                this formula:
 |
 |                                # of grams of fat  *  9
 |                percentage = ----------------------------- * 100
 |                                calories in a serving
 |
 |        Input:  The user is required to enter the grams of fat in one
 |                serving of the food in question, and the total number of
 |                calories in that one serving.  It is expected that the
 |                user will type these two pieces of information at his or
 |                her keyboard.
 |
 |       Output:  The program will display an explanation of its purpose,
 |                will prompt the user for the input, and will display the
 |                percentage of the food's calories that are due to fat.  All
 |                output is displayed on the user's screen.
 |
 |   Techniques:  The program's steps are as follows:
 |
 |                      1.  The program displays its purpose
 |                      2.  The user is prompted to enter the grams of fat
 |                              and calories per serving
 |                      3.  The percentage of calories due to fat is
 |                              computed
 |                      4.  The percentage is displayed to the user, along
 |                              with the given input information.
 |
 |                No particular algorithms are used.  The Java IO package
 |                is accessed to perform console I/O and thus avoid use
 |                of a third-party I/O package.
 |
 |   Required Features Not Included:  All required features are included.
 |
 |   Known Bugs:  None; the program operates correctly.
 |
 *===========================================================================*/


import java.io.*;          // For access to console I/O classes and methods

public class Calories
{
    public static final double CALORIES_PER_GRAM = 9.0;  // a gram of fat
                                                         // has 9 colories

    public static void main (String[] args)
    {
        BufferedReader keyboard;    // input stream
        int    gramsOfFat = 0,      // number of grams of fat in one serving
               totalCalories = 0;   // number of calories in one serving
        double fatFraction,         // fraction of calories due to fat
               percent;             // percentage of total calories from fat


        System.out.print("This program will tell you what percentage "
                       + "of the calories in a serving\n"
                       + "of a food are from the food's fat content.\n\n");

                /*
                 * Read input from the keyboard
                 */

        keyboard = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("How many grams of fat are in one serving?  ");
        try {
            gramsOfFat = Integer.parseInt(keyboard.readLine());
        } catch (IOException e) {}

        System.out.print("How many total calories are in one serving?  ");
        try {
            totalCalories = Integer.parseInt(keyboard.readLine());
        } catch (IOException e) {}

                /*
                 * Compute the percent of calories due to fat
                 */

        fatFraction = (gramsOfFat * CALORIES_PER_GRAM) / totalCalories;
        percent = fatFraction * 100;

                /*
                 * Pretty-print the input and results to the screen.
                 */

        if (gramsOfFat == 1) {
            System.out.print("\nA food with 1 gram of fat ");
        } else {
            System.out.print("\nA food with " + gramsOfFat + " grams of fat ");
        }

        if (totalCalories == 1) {
            System.out.print("and 1 calorie per serving\n");
        } else {
            System.out.print("and " + totalCalories
                           + " calories per serving\n");
        }

        System.out.print("has " + twoPlaces(percent)
                       + "% of those calories from fat.\n");
    }


       /*--------------------------------------------------- twoPlaces -----
        |  Method twoPlaces (Calories)
        |
        |  Purpose:  By default, Java will display floating point values
        |      to a large number of decimal places.  This method rounds
        |      the value to two decimal places, which makes the
        |      value easier to read when displayed.
        |
        |  Pre-condition:  A floating point value of the form *.def* has 
        |      been supplied, where a letter represents one digit and '*'
        |      represents 0 or more digits.
        |
        |  Post-condition: The given floating point value is returned
        |      in the form *.dg, with g=e if f < 5, or g=e+1 if f >= 5.
        |
        |  Parameters:
        |      number (IN) -- the floating point value to be modified
        |
        |  Returns:  number rounded to two decimal places
        *-------------------------------------------------------------------*/

    public static double twoPlaces (double number)
    {
        double shiftRight, // number with . moved two places to the right
               rounded,    // shiftRight w/o extraneous digits
               shiftLeft;  // rounded with decimal point restored

        shiftRight = number * 100;
        rounded = Math.round(shiftRight);
        shiftLeft = rounded / 100;

        return shiftLeft;
     }
}
In this program, I decided that it would be nice if the output wording matched the values the user entered. The IF-ELSE statements will make the words match the quantity; for example, "1 gram" instead of "1 grams". This step wasn't required, but it does make for a more polished final program. The twoPlaces method helps clean up the output by reducing the number of digits shown after the decimal point.

And here's what the user will see when s/he runs it:

$ javac Calories.java
$ java Calories
This program will tell you what percentage of the calories in a serving
of a food are from the food's fat content.

How many grams of fat are in one serving?  3
How many total calories are in one serving?  170

A food with 3 grams of fat and 170 calories per serving
has 15.88% of those calories from fat.


Step #5: Double-Check Your Work
I can't begin to relate to you how frustrating it is for me to have to take off points just because the student didn't take the time to double-check that their program is really complete. When you think that you are done, try running through this little check-list and see if you really are done:
  1. Have I reread the assignment handout to make sure I found all of the requirements?
  2. Does my program meet all of the requirements?
  3. Is my documentation complete? (Did I finish the external documentation? Are my variable names meaningful? Are the variable declarations documented? Did I use white space effectively? Did I include an internal block comment for each method?)
  4. Did I run my program on all of the provided test data (if any)?
  5. Did I create my own test cases and verify my program's correctness on them?
  6. Did I check the results by hand to ensure that the program's logic is correct?
  7. Have I printed out everything that I need to turn in?
  8. Did I electronically submit my program according to the instructor's directions?
If everything looks good, then you're ready to hand it in.


Want to learn more about good programming style? Please visit my Programming Style Documents page for pointers to additional documents about programming style.

Do you have a comment on this page? I'd like to hear it; you can email me at mccannl@acm.org.