CPSC 124 (Fall 1998): Lab 2
Programming in the Small


WELCOME TO THE SECOND LAB for Computer Science 124: Introductory Programming, Fall 1998. In this lab, you will write fairly short programs that use if and while statements. This is "programming in the small," concentrating on what goes on inside individual subroutines. Before you can hope to write complex programs, you have to know how to design the algorithms and write the code that are used in subroutines, since ultimately it's inside subroutines that everything actually gets done.

As usual, you will find a set of exercises at the end of this lab. You should turn in your answers to the exercises in class on the Monday following the lab. If you work with a partner in the lab, you and your partner have the option of turning in separate reports, or turning in one report with both your names.

Before you do anything else in the lab, you should copy the files that you'll need into your own account. You can do this with the command

cp  -r  /home/cs124/lab2  ~

After copying the files, you should change your working directory with the command

cd  lab2


Outline of the Lab:


Roll the Dice

Computers can simulate random events with pseudorandom numbers. Pseudorandom numbers are not really random. The computer calculates a sequence of pseudorandom numbers according to some definite rule. However, the sequence of numbers is random enough for most purposes. Furthermore, when you run a Java program that uses pseudorandom numbers, the computer starts the sequence at a value based on unpredictable quantities such as the time of day and the amount of computation time that has been used by the CPU since you logged on. This is why the program uses a different sequence of numbers each time it is run.

In Java, you can tell the computer to generate a pseudorandom number by calling the function Math.random(). This function returns a pseudorandom real number that is greater than or equal to 0.0 and strictly less than 1.0. If you want N to be a pseudorandom integer in the range from 0 to N-1, you can say

N = (int)( N * Math.random() );

If you would prefer a random integer in the range from 1 to N, you can add one:

N = (int)( N * Math.random() ) + 1;

In any case, each of the possible values of N is equally likely. You can simulate rolling a die -- the singular of dice -- by choosing a random number in the range from 1 to 6. To simulate rolling a pair of dice, you should roll each die separately and add the results, giving a number in the range 2 through 12.

Here is a very simple program that simulates rolling a pair of dice and reports the results to the user:

      public class Dice {

         public static void main(String[] args) {

            int firstDie  = (int)(6 * Math.random()) + 1;  // Roll one die.
            int secondDie = (int)(6 * Math.random()) + 1;  // Roll the other die.
            int totalRoll = firstDie + secondDie;          // Total of the two dice.

            System.out.println("The dice came up " + firstDie + " and " +
                                    secondDie + " for a total of " + totalRoll);

         }  // end main()

      } // end class Dice

You will find this program is the file Dice.java, and the compiled program in Dice.class. You can run the program with the command "java Dice".

For your first exercise of the lab, you will write a simple program based on Dice.java. In this program, instead of rolling the dice just once, you will roll them over and over. At the same time, you'll get some useful practice in counting.

For your program, you should roll the dice over and over in a while loop until the roll comes up 7. You should count the number of rolls that it takes to get a 7. (That is, every time you go through the loop, you should add 1 to a counter.) At the end of the program, report the value of the counter to the user. The output of the program might look like this, for example:

          The dice came up 3 and 2 for a total of 5
          The dice came up 6 and 5 for a total of 11
          The dice came up 6 and 3 for a total of 9
          The dice came up 4 and 3 for a total of 7

          It took 4 rolls to get a 7

In this case, it is easiest to use a loop that begins with while (true), and break out of the loop when a 7 is rolled. If you want, you can simply edit the existing program, Dice.java, to make your program, rather than starting a new file from scratch.


A Measurements Conversion Program

For the second exercise of the lab, you will write a program that converts measurements from metric to English units and vice versa. You should implement conversions between inches and centimeters, between feet and meters, and between miles and kilometers. You will need the following facts:

         x inches = 2.54*x centimeters      x centimeters = x/2.54 inches
         x feet   = 0.3048*x meters         x meters      = x/0.3048 feet
         x miles  = 1.60934*x kilometers    x kilometers  = x/1.60934 miles

The user will type in a measurement in the form of a number followed by the units of measurement, such as "3 km", "10.7 in" or "2.232 m". The units of measurement will always be expressed using one of the abbreviations: in, cm, ft, m, mi, or km. Your program should do the appropriate conversion and print the result. (Convert inches to centimeters, centimeters to inches, feet to meters, meters to feet, miles to kilometers, or kilometers to miles.) Continue reading and processing the user's input in a while loop, until the user enters a value of 0 for the number. Here is an applet that simulates the program you should write. Try it!

There are several tricky bits in this program that you need to know about. First of all, how will you read both a number and a unit of measure from the same line? Well, if you use TextIO.getDouble() to read the number, then you can use TextIO.getlnWord() to read the next word from the same line. (See Section 2.4 in the text for a complete discussion of TextIO.) In your program, this might look like:

          double measurement = TextIO.getDouble();
          String units = TextIO.getlnWord();

The second question is, how can you test what unit of measurement the user entered. For this, you need to do comparison of Strings. As explained in Section 2.9, you can do this with the equals() method or with the equalsIgnoreCase() method from the String class. For example, if units is a String that holds the unit of measurement that was entered by the user, then you could say something like:

            if (units.equalsIgnoreCase("in")) {
                .
                .  // convert inches to centimeters and print the results
                .
            }

With these hints in mind, you should be able to complete the program without too much difficulty. If you run into difficulty during the lab, ask for help! And remember to save some time during lab for the next exercise.


Sound! Graphics! Action!

In the first two exercises, you wrote Java programs. This means, more or less, filling in the main() routine to tell the computer what to do when the program is run. As you write your main() routine, you can call on other subroutines that already exist, such as Math.random(), TextIO.getInt(), and equalsIgnoreCase(). For the third exercise of the lab, instead of filling in a main() routine in a program, you will fill in a couple of subroutines in an applet. The ideas is basically the same.

The applet that you create will display an animation of some sort. An animation consists of a sequence of "frames". Each frame is a still picture, but there are small changes from one frame to the next. As the frames are displayed one after the other, the eye perceives the changes as motion.

You don't have to worry about doing the actual animating. That is already handled by a class called SimpleAnimationApplet.class. Since this is object-oriented programming, you can extend this class without understanding how it works. All you have to do is provide a subroutine that can draw each of the individual frames.

The SimpleAnimationApplet class is described in the second half of Section 2.6 of the text, and I won't repeat the details here. In that section, you'll also find a sample animation. The source code for that sample is the file MovingRects.java. There is a copy of this file in your lab2 directory. You can use this file as a basis for your own animation. Use "FirstAnimation" as the name of your applet, and "FirstAnimation.java" as the name of the source code file for your applet. So, you should copy the MovingRects.java file to FirstAnimation.java and then edit the new file. The copy command that you need is "cp  MovingRects.java  FirstAnimation.java". When you edit the file, don't forget to change the name of the class to FirstAnimation!

For your animation, you can write an applet that shows "moving lines" like this one:

This is an easy modification of the MovingRects applet. If you prefer, you can design your own animation. For example, perhaps you would like to be more ambitious and show two groups of lines moving in different directions. Note that to do this, I first filled the applet with blue lines on a red background, just like the previous example. Then, on top of that, I drew a smaller blue rectangle with red lines:

For a completely different example of animation, you can look at the Web page BackAndForth.html. In addition to animation, this applet uses sound. It's easy to use sound in an applet, if you have the sound in a file of the correct format. The file simply needs to be in the same directory with your HTML page and compiled applet. In the applet you can use the statement

             play(getDocumnentBase(), filename);

where filename is a String giving the name of the file that contains the sound. See the source code, BackAndForth.java, for an example. In case you would like to experiment with sounds, I've included a few sound files in the lab2 directory: boink.au, click.au, whoosh.au, gong.au, and goofed.au.

Remember that to run an applet, you need an HTML page. There is a sample HTML page in the lab2 directory that includes an applet named "FirstAnimation". The name of this file is FirstAnimation.html. Assuming that "FirstAnimation" is the name that you use for your animation applet, then the commands for editing, compiling, and testing your applet are:

                nedit FirstAnimation.java &
                javac FirstAnimation
                appletviewer FirstAnimation.html

After you get your applet working, you should publish it on your Web page. I suggest that you replace my maze applet on your page with your animation applet. To do this, replace the lines

        <applet code="Maze.class" width=310 height=210>
            <param name="rows" value="21">
            <param name="columns" value="31">
        </applet>

in your index.html file with the lines

        <applet code="FirstAnimation.class" width=300 height=200>
        </applet>

Use a different width and height if you want. You also need to copy all the relevant files from your lab2 directory to your www directory. You need the compiled class file, FirstAnimation.class. Since this class depends on the SimpleAnimationApplet class, you also need to copy SimpleAnimationApplet.class. If you decide to use any sound files, you have to copy them too. Working from your lab2 directory, you can use the commands:

                 cp  FirstAnimation.class  ~/www
                 cp  SimpleAnimationApplet.class  ~/www

to copy the class files.


Exercises to Turn in

Exercise 1. (6 points) Turn in a printout of your dice program, which counts how many rolls it takes to get a 7. Make sure that your program follows the rules of good programming style, including rules about comments, formatting, and variable names.

Exercise 2. (8 points) Turn in a printout your Metric Measurement Converter program. It should, of course, follow the rules of good style. You can, if you like, expand it to handle other units of measurement besides inches, centimeters, feet, meters, miles, and kilometers.

Exercise 3. (8 points) Turn a printout of your animation applet. Also, add the applet to the index.html file in your www directory so that it shows up on your home page. I expect to be able to see your applet running on the Web. (If you are working with a partner, please make sure I know whose page to look at.)

Exercise 4. (8 points) Section 2.5 of the text discusses the use of stepwise refinement and pseudocode to develop algorithms. For this final exercise, you should pretend that you have not already written the measurements conversion program from Exercise 2. Read Section 2.5 carefully and use the methods discussed in that section to develop an algorithm for a measurements conversion program. Write up a description of the development process. Imitate the discussions in the text. Your answer should include at least four pseudocode outlines of the algorithm. Each outline should be more detailed and complete than the previous outline. Also include some discussion between stages, as is done in the examples in the text. This exercise will certainly require at least two pages, to do it right! (Note: If you prefer, you can do the same exercise for your animation applet instead.)


[ Lab Index | Online Notes ]