How to Develop Your First Java Program

Some over your shoulder advice on how to start transforming a problem description into a program.

©2002–2008 by Wayne Pollock, Tampa Florida USA.  All Rights Reserved.

 

Too many students, knowing the for loop just discussed in class must be used on the next programming assignment, will typically start by opening an editor window, type in a for loop, and then wonder how to fit to the program around the loop.  If by adding this and that a working program results, then comments are added, the program is properly indented, and in short the program is made "pretty" for the teacher.  Often such students never get a fully working program.

The trick with using loops, if statements, switch statements, and other control structures in your programs is that you need to approach programming from the other end.  What I mean is, rather than try to fit some control structure into your program, try to design your program without worrying where and how to use control structures.  Often you can design your program using flowcharts, UML diagrams, but one easy way is to just write a series of short English (not Java) sentences that outline the tasks needed, using indenting to show blocks.  This is usually called pseudo-code.

It never pays to try to write the program before you understand how to solve it (in English).  Once you have a design, the programmer's job is to translate the design into legal Java.  This step is much easier than developing the design.  Trying to design a program while implementing it at the same time is nearly impossible, not cost effective (that is, this way takes longer), and results in poor quality programs.

Learning how to take a problem description and come up with a design is a skill that takes lots of time to develop. There is no magical step by step formula you can follow to develop a program. (If there were, no one would pay programmers to write programs, there'd be a program to do it!)  You should start by restating the word problem as a series of smaller, definite (that is, not vague) sub-tasks that if solved would solve the overall problem.  (This is known as "top-down design" and works well for small procedural tasks.  Later in the course we will learn "object-oriented design", which works better for many programs, especially larger ones.)

Here is some good advice from Patricia Shanahan, the first 4 items (slightly edited) from her article So, You Need to Write a Program but Don't Know How to Start.

Below is a sample verbal problem description.  I will try to show how one might go about the process of designing and creating a program to solve the problem.  I hope this will give the reader some insight on how to approach their first programming assignments.

Sample Task:

Write a non-GUI program that displays the square root of the first 10 integers.

(My thinking out loud while I solve this problem is shown in italics:)

It seems I need to do something 10 times.  That sounds like a "counting" type of loop.  The loop and the tasks I need to do for each number might look something like this:

For every number 1 to 10:
compute it's square root
display the result

I should probably also display a title of some sort, but these steps seem to be all that's needed if I were solving this problem by hand.  It's also clear by this point that the loop will be a for loop.  No additional control structures or steps appear to be required.  Also, the steps (at least for now) appear short and simple, so breaking the program down with one task per method doesn't seem necessary here.  The completed first draft design therefore looks like this:

Display a title
For every number 1 to 10:
compute it's square root
display the number and the resulting square root

Hmm, this looks easy except for the computing the square root step.  I wonder if there is a standard method for this, or do I have do figure out how to compute square roots?  Well, if there's a method for this already it's probably in the Math class.  Let's look in the javadocs...(clicking on java.lang package, click on Math class)...  Aha!  There's a static Math.sqrt method.  (If there wasn't one I would look elsewhere, maybe in the java.math package, then in the index of my textbook, and finally I would search Internet resources.  If all else failed I would ask the instructor, or consult a math text to find an algorithm (or maybe a whole program) to compute a square root.)

Ready to start programming!  Here's the first version, which is just a skeleton:

// Program to print the square root of first 10 integers.
// Written 2002 by Wayne Pollock, Tampa Florida USA.

class SqRoots
{
    public static void main ( String [] args )
    {
        // display a title

        for ( int i = 1; i < 10; ++i )
        {
            // Compute the square root of i
            // Display the square root of i
        }
    }
}

So far this is standard stuff:  The comments, the class with a main and major control structures, and my sub-tasks put into the skeleton program as comments.  You should always start with a skeleton like this for all programs, especially putting in the comments.  But looking over this program, the 10 bother's me.  I really should make that a constant so I can easily change it later and to make the program more readable.  I'll change that in the next version by adding a "static final int N" as a property, a reasonable choice for an int constant.  (I wish I could use a longer, more descriptive name for this constant than "N", but I can't think of one I like!)

To display the title is easy, since this is a non-GUI program we can just use System.out.println:

System.out.println( "Square Roots Table" );
System.out.println( "------------------" );

The line of dashes gives a jazzy "underline" effect.  (Hope I get extra credit for it! :-)

The square root can be computed and displayed in a single step.  There doesn't seem to be any reason to put the square root into a variable and then display the variable.  (In general it pays to avoid unnecessary variables; the program will be simpler and perhaps more readable.)  If I later decide to use that same value again, I can go back and save the result in a variable (or even save all results in an array).  But for now there's no reason to save the result, so we'll just calculate it and print it out in one step.

Using System.out.println for each number outputs each value on a separate line.  (System.out.print doesn't do that).  Looking at the assignment directions again, there doesn't seem to be any requirement for the appearance of the output.  I think the results look best in a table form, so let's output the number (that is, the value if i) first, than a tab (to line up the second column), then the result.

A good idea when there seems to be incomplete requirements is to ask the instructor for a clarification, something such as Is there any specific output format required?  If so, could you provide a sample of the required output format?  If not, would a two-column table format be acceptable?

Note that if using GUI output, you don't use println or tabs to line up columns.  But that doesn't apply to this non-GUI program.  Java allows us to concatenate numbers and strings into a single string which can be used as an argument to println.  This seems the most straight-forward way:

System.out.println( i + ":\t" + Math.sqrt( i ) );

(Notice the extra colon, which give a nice professional or polished look to the output.)  That's all the pieces done!  Here's the complete program (first draft):

// Program to print the square root of first N integers.
// Written 2002 by Wayne Pollock, Tampa Florida USA.

class SqRoots
{
    static final int N = 10;  // How many square roots to compute.

    public static void main ( String [] args )
    {
        // Display a title
        System.out.println( " Square Root Table" );
        System.out.println( "-------------------" );

        for ( int i = 1; i < N; ++i )
        {
            // Compute and display square root of i
            System.out.println( i + ":\t" + Math.sqrt( i ) );
        }
    }
}

Here's the output after I compile the program with the command javac SqRoots.java and run it with java SqRoots :

 Square Root Table
-------------------
1:	1.0
2:	1.4142135623730951
3:	1.7320508075688772
4:	2.0
5:	2.23606797749979
6:	2.449489742783178
7:	2.6457513110645907
8:	2.8284271247461903
9:	3.0

Hmm, this works...except that I only got 9 numbers, not 10!  Usually one-off errors like this mean that something is wrong with the loop.  Oh, I see the bug:  I should have used "<=" not "<" in the for loop.  How embarrassing!

Also I don't like how the numbers or title displays.  The numbers should all have the same number of decimal places showing (the last digit shown should be rounded), and the title doesn't appear centered over the table.  Java provides number formatting classes I could use to do this, and Java 5 added a printf method to format output without creating lots of objects and using many method calls.  I will worry about that in version 2, to force customers to buy an upgrade.  (Just kidding!)

Meanwhile here is the final, cleaned-up program with line numbers added (Download SqRoots.java):

// Program to print the square root of first N integers.
// Written 2002 by Wayne Pollock, Tampa Florida USA.

class SqRoots
{
    static final int N = 10;  // How many square roots to compute.

    public static void main ( String [] args )
    {
        // Display a title
        System.out.println( "\n Square Root Table" );
        System.out.println( "-------------------" );

        for ( int i = 1; i <= N; ++i )
        {
            // Compute and display square root of i
            System.out.println( "   " + i + ":\t" + Math.sqrt( i ) );
        }
    }
}

And here's the final output:


 Square Root Table
-------------------
   1:	1.0
   2:	1.4142135623730951
   3:	1.7320508075688772
   4:	2.0
   5:	2.23606797749979
   6:	2.449489742783178
   7:	2.6457513110645907
   8:	2.8284271247461903
   9:	3.0
   10:	3.1622776601683795

All done!  Time to party!


For more good advice to beginner (newbie) programmers, see Starting Writing a Program by Patricia Shanahan.  A few good points to consider:

(For more information on designing programs see How to Design and Develop a Java Program.)