CPSC 124: Lab 2
Program Building Blocks


IN THIS LAB,YOU BEGIN working with the fundamentals of programming in Java: variables, types, assignments statements, basic input/output, loops, and if statements. You'll be writing simple programs using all these features. In the process, you'll also learn more about using the Metrowerks CodeWarrior programming environment.

This lab is based on material covered in Chapter 2 in the notes for this course.

For this lab, you will be working with console input and output. You should start with a copy of the "Java Console Ap Starter" folder from the Math/CS Server. Drag a copy of this folder onto your computer. You might want to rename the copy something like "Files for Lab 1". At the end of the lab, you should copy your work onto a floppy disk. It's actually a good idea to make two copies on separate disks, just to be safe. It's not a good idea to leave a copy of your work on a computer in the lab. Any files that you create on a computer in the lab should be deleted before you leave. (Drag the folders or files that you want to delete into the trash, then empty the trash with the Empty Trash command from the Special Menu.)

Open your copy of the Console Ap Starter program, and double-click on the project file, JavaConsoleAp.proj. This will start up Code Warrior and open the project.

The project window lists two files, Console.java and Application.java, which contain Java program code. This illustrates a general fact about Java programs: they can be spread out over many different files. One file can define subroutines (that is, commands) that can be used in another file. The purpose of using multiple files is to break things down into small pieces that are not too complicated individually, rather than to try to throw everything into one huge, complicated file that would be too difficult to understand all at once. In this project, the file Console.java defines certain input/output commands. You will be working in the other file, Application.java, where you can use those commands. (You can look at Console.java if you want, but you don't have to understand it. You will use the commands from this file as "black boxes.")


Open the file Application.java by double-clicking on its name in the project window. This is what you will see, except for the colors. The lines shown here in green are the part that you have to change when you want to write a new program.

   public class Application {

      public static void main(String[] args) {
   
         Console console = new Console();  // open console window
      
         console.putln("Hello World!");
         console.putln();
         console.put("Press return... ");
         console.getln();
      
         console.close();  // close console window
      
      }  // end of main()
   
   }  // end of class Application

You will be writing and running a number of programs based on this one. It will be a good idea to keep the programs in separate files with different names. Let's go through a few simple examples so you know how to do this. Start with a program that asks the user to input two integers, and then prints out the result of multiplying those two numbers together. When the program runs, the console window should look something like this, with the stuff that the user types shown here in red:

        Type in a number: 17
        Type another number: 42
        The product is 714

Your program will use three variables of type int. It will use the commands console.put and console.getlnInt. (You could use console.getInt() instead of console.getlnInt(), but I recommend the "getln" versions of input commands unless you actually want to read several values from one line of user input.) You'll also need an assignment statement to do the multiplication.

Before you run your program, you should save it under a new name. Do this using the Save As command in the file menu. Make sure the file you want to save is in the front window on the screen, then choose "Save As..." from the file menu. In the dialog box that pops up, enter a new name for the file, such as TestProgram1.java. Also check that the file is being saved in the correct folder. Then click on the Save button to save the file. You'll see that a new file has been created. You should also see the name of the new file in the project window in place of the name Application.java. This means that when you give a Make or Run command, it's your new program that will be compiled or run.

Now it's time to compile and run your program. The easiest thing to do is to use the Run command. (As with many commands in Code Warrior, you have the option of choosing the command from a menu or clicking on a small icon in the toolbar at the top of the screen.) The Run command does the following:

You have other options besides using the Run command: The Make command will do the first two steps without running the program. The Compile command is used to compile a single file. And Bring Up To Date will compile all the files that need to be compiled. For the most part, though, it's easiest to stick with the Run command which does everything.

After you have a run a program, you should be sure to Quit from the Metrowerks Java interpreter if you want to go back and make any changes to the program. It's stupid that you need to do this, but Code Warrior won't be able to link a new program if the old program which it wants to replace is in use by the interpreter.

Once you get your simple program running, add some variety to it by making it do either multiplication or addition. The user should be able to select which operation to apply by typing in either * or +. Use an if statement to decide whether the user typed a *. When you run the program, the output might look like

             Type in a number: 17
             Type another number: 42
             Type * to multiply or + to add: *
             The product is 714

or like

             Type in a number: 5
             Type another number: 3
             Type * to multiply or + to add: +
             The sum is 8

You will need a new variable of type char for reading the user's input, and you will need to use the command console.getlnChar(). To review, the steps for writing and running this program are:

Run your program several times to make sure that it is working correctly.


The exercises that you will turn in for this lab include several programs and one short essay. For each programming exercise, you should turn in a print-out of your program. The program must be properly commented. The comments on a program must include at least: your name or names, a description of the purpose of the program, and a statement of the purpose of each important variable that you declare. The variable names you use should be meaningful, where appropriate. The program should be indented to show its structure.


Exercise 1

It's fun to talk to your computer, or at least to type to it. A program can ask the user questions, record the user's responses in variables, and than use that information to do some calculation and to produce some output.

For practice at doing input and output, write a program that asks the user some questions. Get the user's name, address, and year of birth. Ask for some other information, like a favorite number. Store all the responses in variables of appropriate types. After reading in the information, print out a report, something like this:

        Your name is David
        and your address is Lansing 301.
        You were born in 1953.
        That means you are 43 years old this year.
        Your favorite number is 42.
        Gee, that sounds sort of familiar.
        Did you know that a circle of radius 42 has an area of 5541.76?

You can be creative. Your object is just to get some practice with using the console for input and output, to declare and use variables, and to do a few simple calculations.

(I'll repeat one more time: Your programs should be nicely indented, they should use meaningful variable names, and they should include comments, as described above. This applies to any program that you turn in for grading.)


Exercise 2

Computers can be used to run simulated experiments. The computer can perform many simulated experiments in the time it might take to do one experiment in the real world. (Of course, this doesn't do you much good unless the computer experiments are valid simulations of the real things.) For this exercise, you should write a program that will perform the experiment: See how many times you have to roll a pair of dice to get a double six, that is a total of 12 on two dice. You program will do this by rolling "simulated dice." A pseudocode algorithm for the program is:

           Initialize a counter to zero;
           do {
              roll the dice;
              add 1 to the counter;
           } while (the sum of the dice is not equal to 12);
           Print the counter (which is the number of rolls);

This is a simple program, except for the question of rolling a die. Rolling a die can be simulated by choosing a random integer between 1 and 6. You can do this in Java with the command:

           die1 = 1 + (int)(Math.random() * 6);

Where die1 is a variable of type int. If you want to roll two dice, you can do the same thing with another integer variable, die2. Then the total roll for the two dice is given by die1 + die1.

(You don't particularly need to understand why the above statement gives an integer between 1 and 6. But if you are interested, the reason is as follows:

           -- Math.random() is a number in the range 0 <= x < 1
           -- (Math.random() * 6) is a number in the range 0 <= x < 6
           -- (int)(Math.random() * 6) converts the real number,
                  (Math.random() * 6) into an integer by throwing away
                  any part of the number that comes after the decimal
                  point.  The result is an integer in the range 0 to 5.
           -- Finally, 1 + (int)(Math.random() * 6) is an integer
                  in the range from 1 to 6.  Each of the possible
                  numbers is equally likely to occur, just as when
                  you roll a fair die.)

Write the program and run it several times. You'll probably get a different answer each time you run the program.


Exercise 3

We could continue beyond Exercise 2 by asking, "What is the average number of rolls that it takes to get a 12?". To answer this question, you would repeat the experiment from Exercise 2 a large number of times, add up all the results, and divide by the number of experiments to get the average.

Writing a program to do this is Exercise 4. Exercise 3 is to develop an algorithm for the program. Start with a general outline of the algorithm, written in pseudocode. Then refine that algorithm in several stages until you get a complete algorithm that can easily be translated into a program. Discuss what you are doing at each step. Write up your work in the format of the case studies from Section 2.5, and turn in your write-up as Exercise 3 for this lab.


Exercise 4

Exercise 4 is to write a working program based on the algorithm you developed for Exercise 3. If you like, you can improve your program by asking the user:

There is a sample program on the server called RollTheDice. You can run this program to see how your program should work.


[ Lab Index | Online Notes ]