CS 455 Programming Assignment 1

Spring 2022 [Bono]
Due date: Wednesday, Feb. 2, 11:59pm Pacific Time


In this assignment you will write a graphics-based program to simulate someone tossing a pair of coins some number of times, and display the results. So for example the user may request 10 trials. For each trial two coins are tossed. The program reports in bar graph form how many times the result was two heads, how many times it was two tails, and how many times it was one of each.

This assignment will give you practice with creating and implementing classes, using loops, using the java library for random number generation, doing console-based IO, drawing to a graphics window, and writing a unit test. Also you'll get practice in general program development. Please read over the whole assignment before beginning: in particular, do not wait until the assignment is due to read about submitting it because you'll want to do your first submit before the final deadline, because when you submit it we do some checks on your code, and you will be able to resubmit if you fail those checks (but not if you are out of time).

This document may seem voluminous, because it includes some instructional material, and hints on how to do certain things. You'll need to read it or parts thereof more than once, possibly skimming some parts on the first reading. To help you find things as you are working on the assignment, here is a table of contents for the main sections:

Table of Contents


The programming environment for this assignment

Reminder: The first time you access the assignment on Vocareum, you will need to go through the link on d2l (More detailed directions about this were given on Lab 1). Any subsequent accesses to the same assignment can be made via labs.vocareum.com.

In the normal Vocareum configuration, you have a Linux terminal, but no way to run a program with a graphical user interface (GUI). For this assignment we are using a different Vocareum configuration that will allow you to open multiple windows, including a separate one to run your GUI program. With this configuration, when you start up Vocareum for this assignment, it will not start up a terminal in the workbench window (i.e., the usual one you use), but you use a virtual Linux desktop instead.

How to start up a virtual Linux Desktop in Vocareum
The way you get to a virtual linux desktop in this assignment is to go to a menu that's on the upper right of the workbench window: choose Actions--> Applications --> Desktop.

That will open a linux desktop in another tab in your browser. If it starts with a pop-up dialog, choose "Use default configuration." There are a few ways to open a terminal window in this desktop. You can use the Applications menu at the top left of the screen, and choose "Terminal Emulator". Or you can right click anywhere on the desktop, and choose "Open Terminal Here".

Warning: depending on how you started up terminal, it might not start out in your home directory (i.e., "work"), but rather starts in the root directory ("/") or somewhere else. So the first thing you should do is

to get into your home directory. (One way to check if you are in your home directory is you will see the ~ (tilde) right before the $ in the shell prompt.)

Your home directory will be populated with the starter files we are providing you. Part of what we provided is source code for a complete sample Java GUI program there, so you can try out compiling and running such a program in this environment before you write code for your own program. Compile and run this program:

javac CarViewer.java
java CarViewer
More about this car example (from Section 3.8 of the textbook) later.

You can switch between these two tabs in your browser to switch between editing (normal Vocareum window), and compiling and running (Linux desktop). To make it easier to see your compile errors at the same time as you view your source code, you can put the Vocareum tab in a different browser window altogether.

Another option with the desktop is to use one of the other source code editors available within the desktop itself. I saw emacs and vim (Rt-click on desktop-->Applications-->Accessories). I'm not sure how fast these work on this platform, so if you end up using one of these, let me know how it goes. (I only opened emacs there briefly once; it started up pretty fast, so that's a good sign.) Both emacs and vim are a little different than other editors you are used to, so you probably would want to take a look at an online tutorial on the web before using them. Eclipse is also available there; it may be somewhat slower than running it locally.

You can disconnect from the Desktop by closing the tab, or in the main Vocareum window (upper right) do: Actions-->Applications-->Stop App. Then you can restart later the same way you did the first time.

Using another IDE for this assignment
If you don't want to use Vocareum and its Linux desktop as your development environment, you can use another IDE running locally on your own machine.

If you choose go this other route, you would do the following:

  1. Install and try out another IDE. There are a few tutorials in the Java section of the Documentation page to help you get started with IntelliJ or Eclipse.
  2. Download the starter files for the assignment into a folder on your laptop (e.g., call it pa1). The easiest way to do this is, from the Vocareum PA1 assignment workbench do: Actions-->Download starter code (menu on the upper right).
  3. Get your program working, tested, and completely documented on your laptop IDE, and when you are ready to turn it in . . .
  4. Upload your complete program into Vocareum. In the Vocareum workbench, click Upload (button in the upper-left area), and you will get a file browser that will allow you to select multiple files to upload. You will only need the source code files (and README), no .class or project files. Do not wait until the final due date/time is imminent before uploading and testing it on Vocareum.
  5. Compile and completely test your program again on Vocareum. You want to make sure what you wrote will run in the Vocareum environment, because it is the grading environment. This also helps you to make sure that you are going to be submitting the correct version of your solution.
  6. Submit your assignment on Vocareum. Please read the details about submitting this in the section on it at the end of this document.

The assignment files

The files in bold below are ones you create and/or modify and submit. The ones not in bold are files you will use, but that you should not modify. The ones with a * to the left are starter files we provided.

For more information about the classes mentioned above see the section on class design.

The assignment

Initially your program will prompt for the number of trials to simulate (a trial is two coin tosses) on the console (i.e., terminal window), error checking that a positive value is entered. (More details about error checking here.) This part of the program will be console-based, to keep things simpler.

Then it will run the simulation and display a 500 tall by 800 wide pixel window with the results of that simulation. The results will consist of three labeled bars, each a different color, to show how many trials had the specified outcome. The label will show what the outcome was (e.g., Two Heads), the number of trials that had that result, and the percentage of trials that had that result (rounded to the nearest one percent). Because the simulation uses random coin tosses (simulated using a random-number generator) subsequent runs with the same input will produce different results.

Here is a screen-shot of output from one run of our solution to this assignment, where we do 1000 trials:

  trials output

Remember, your output will not be identical to this because of the random nature of the results. As you can see in this example, because of the rounding, depending on the results, the total of all the percentages might not add up to exactly 100%.

Note the placement of each of the bars evenly across the window. In addition, the height of each bar is given so that 100% would fill up most of the height of the window (but not run into the top of it). Thus the 49% of trials that resulted in a head and a tail in the example above fills up roughly half of the height of the window.

Also, your bar graph should get resized appropriately if the window gets resized. As mentioned in the textbook, every time a window gets resized or iconified and de-iconified paintComponent gets called again. Here's a later screen-shot created during same run shown above, but after the window had been resized:

Note that resizing the window does not change the results of the simulation.

Here's an example illustrating what the display looks like when all of the trials have the same result, forced here by only doing one trial: Note that the bar does not touch or run off the top of the screen)

More about the graphics library methods necessary to get these results in the section on Graphics programming.

There are a few other requirements for the assignment discussed in the following sections. To summarize here, the other requirements are:

More details of the error-checking

As mentioned in the earlier section, when your program prompts for the number of trials, you will error check that a positive value is entered. More specifically, we mean that on an invalid number of trials the program will print out an informative error message and then prompt and read again until the user enters a valid value. Example (user input shown in italics):
Enter number of trials: -5
ERROR: Number entered must be greater than 0.
Enter number of trials: 0
ERROR: Number entered must be greater than 0.
Enter number of trials: 100
Your program does not have to handle non-numeric input. (We will not test it on that case.)

Class design

To help you make your program object-oriented, we are giving you the general class design for this program.
The Car Example
Our program follows the conventions of graphical classes used in the textbook (see Resources, near the beginning of this document, for relevant textbook readings). In particular, this general design follows the car example in Section 3.8 of the textbook that has a viewer, a component, and a graphical object that can get instantiated multiple times and drawn in different locations on the screen (in that one the object class is a Car, here it's the Bar).

We provided you with the source code for that example as part of the starter files for this assignment. You can use the code in CarViewer as a starting point for your CoinSimViewer class for this assignment.

In addition to examining the general structure of the car example code, you can use it to test out running a GUI program in the Vocareum virtual Linux Desktop before developing your own code. When you run it there, you can also see how the display changes when you change the size of the window in which the CarViewer application is running and the corresponding code that gets that to happen (the display for your program will also change when the window is resized).

We also modified CarComponent.java a little bit from the version of the code from the text: we instrumented the code, so you can easily see every time paintComponent gets called, to help you better understand when the Java Swing graphics framework calls paintComponent. To see this, once you start running the program, make sure you can see the terminal window, as well as the CarComponent window; then try resizing the CarComponent window, and minimizing it and opening it again.

You are required to use the following classes (ones in bold are ones you will be creating yourself or implementing): Note: this list doesn't include all the java library classes that will be used in the program; for example CoinSimComponent will need java.awt.Graphics.

Incremental development

Any program of non-trivial size will be developed faster, with fewer bugs, using the technique of incremental development, which means developing, and testing, pieces of the program incrementally. The incremental aspect is that your program may gradually grow until it includes the complete functionality. (Other people use different names for the same thing. Sometimes it's called building subsets.)

A desirable feature of individual classes is that they are as independent as possible from a program that uses them. Some classes, such as String, or ArrayList (which we will see soon) are general-purpose and can be used in many different programs. Other classes are more special-purpose, such as CoinTossSimulator, but still are modules that can be separated from a particular program that uses them. We can test such a module using a unit-test, which is a program specially designed to test the module.

We often unit-test one (or more) classes, and then once we are convinced that unit is working correctly, we can integrate that class with other code that uses it. If this larger code base is now buggy, we can feel fairly certain that the bug is in the new code we added, since we already tested the first class. So any time we find bugs, it's in a small program: much easier than locating bugs in large programs.

Similarly, if we make later changes or enhancements to our application our code will be more robust in the face of these changes because, in our unit-test, we tested the module in ways not specific to how it was used in this application. (As you have experienced as a user, software is always getting changed over time, e.g., the latest version of Windows is in the double-digits.) For example, in this assignment, there are methods and method functionality of CoinTossSimulator that are not used by the program that draws the bar graph, but you would never be sure whether they worked if you didn't test them.

For this assignment, the final product will not be a very large program, but we want to get you in the practice of using incremental development, so you will still be successful when you are trying to develop and debug much larger programs. Even in this program there are at least two distinct issues to deal with: (1) figuring out how to use the random-number generator to do a coin-toss simulation and (2) figuring out how to do the graphics to draw the results of the simulation. It will be much easier you we can deal with these issues one at a time, so you can isolate bugs related to each one more easily. For this assignment you are required to write a console-based Tester class to test your CoinTossSimulator class. This test program is described in more detail in the next section.

Similarly, you could test your Bar class apart from its use in this particular bar graph by creating several bars with hard-coded data or data from the keyboard using a Scanner. We won't require you to submit such a BarTester program for this assignment, however.

Testing the CoinTossSimulator class

You are actually going to submit two programs for this assignment, both of which use your CoinTossSimulator class. One is CoinSimViewer, described earlier, that has a graphical display. The other is a console-based program, CoinTossSimulatorTester, expressly written to thoroughly test your CoinTossSimulator class, without including the drawing functionality of the CoinSimViewer program. The rationale for unit tests was discussed in the previous section. First, here's more information about compiling Java code:

How to compile and run multi-file Java programs on the command line Often you can just list the file that contains main in the compile command and javac figures out what other classes are used in that program and compiles those as well. However, sometimes the Java compiler gets confused when you only have modified some of the source files since the original compile. For running a program that uses multiple class files, the only class name you give as the argument to the java virtual machine is the one containing main.

When you are compiling and running your test program you should be able to do it as follows:

javac CoinTossSimulator*.java
java CoinTossSimulatorTester
The wild-card ("*" symbol) in the compile command will match the two files CoinTossSimulatorTester.java and CoinTossSimulator.java.

For the larger program we are doing for this assignment (for that one main is in CoinSimViewer.java), you can either list all of the files it uses on the command line or use the following convenient shorthand:

javac @CoinSimViewer.list
java CoinSimViewer
The CoinSimViewer.list file (one of your starter files) just consists of the list of files to compile for the program. The @ on the command line tells java to look in the file that follows it find out what java files to compile. An alternate is to use *.java instead in the compile command, although that one would also attempt to compile CoinTossSimulatorTester.java as well as the code for the car example.

As mentioned in the previous section a test program like CoinTossSimulatorTester is called a unit test; we have discussed such unit tests in lecture, and they are also discussed in Section 3.4 of the textbook. One goal of this test program is for you to test the full functionality of the CoinTossSimulator class. However, its use in the CoinSimViewer program does not test the full functionality. In particular, with the CoinTossSimulator you can do multiple calls to the run method to add more trials to the ones already made. AND if you call reset does it reset the simulation back to its beginning state (i.e., no trials done yet).

So, what should you put in your CoinTossSimulatorTester? This will be a console-based program -- i.e., no GUI. It will be a non-interactive program (i.e., fixed data, nothing read in from the user), that tests every method multiple times, printing informative output to the console with the results of each operation. Make sure you also test creating and using multiple instances of the class.

Unlike the unit-test programs in the textbook and lecture, we can't predict the exact results of calls to run, because of the random nature of the program. Instead, write code to test that the sum of the number of two-head tosses, two-tail tosses, and head-tail tosses adds up to the total number of trials. (Hint: In the sample output below, we display true or false for this result by just printing out the result of a boolean expression. So if we ran it on a buggy CoinTossSimulator, it might result in false. NOTE: we WILL be doing such a test on your test program.)

Your output should look like the following. This shows only part of a sample run of our tester program. A few explanatory notes first:

After constructor:
Number of trials [exp:0]: 0
Two-head tosses: 0
Two-tail tosses: 0
One-head one-tail tosses: 0
Tosses add up correctly? true

After run(1):
Number of trials [exp:1]: 1
Two-head tosses: 0
Two-tail tosses: 1
One-head one-tail tosses: 0
Tosses add up correctly? true

After run(10):
Number of trials [exp:11]: 11
Number of trials: 
Two-head tosses: 2
Two-tail tosses: 3
One-head one-tail tosses: 6
Tosses add up correctly? true

After run(100):
Number of trials [exp:111]: 111
Two-head tosses: 28
Two-tail tosses: 30
One-head one-tail tosses: 53
Tosses add up correctly? true

[ . . . output for tests with different number of trials would be here . . .]

After reset:
Number of trials [exp:0]: 0
Two-head tosses: 0
Two-tail tosses: 0
One-head one-tail tosses: 0
Tosses add up correctly? true

After run(1000):
Number of trials [exp:1000]: 1000
Two-head tosses: 265
Two-tail tosses: 229
One-head one-tail tosses: 506
Tosses add up correctly? true

[ . . . output for other tests would be here . . .]

Remember you won't get these exact numbers because of the random nature of the simulation.

Note: When you test a method such as run which has a restriction on its parameter (in this case the restriction is that the value must be greater or equal to one) it means that the behavior of the method is undefined if that precondition is not met. That means that your code for run does not have to handle that case, and your tester program should not test that case.

Hints on graphics programming

Most of the graphics primitives you will need for this program are covered in the graphics sections at the end of Chapters 2 and 3 of the textbook, except for a few things we will discuss here. So, you will not need to go hunting through the online documentation or random web sites to figure out how to do the necessary drawing. More specifically: how to draw a filled rectangle is illustrated in the alien face example in textbook section 2.10.4; and the start of the section of this assignment on class design discusses another example from the textbook that has a similar object-oriented design to this one.

Your program may use a fixed size for the width of each bar, and for the buffer-space between the tallest possible bar and the top and bottom of the window (the solution whose results we showed earlier also does this). Any such constants in your program need to be named constants (see section on grading criteria below, for more information). For the purposes of this assignment you do not have to worry about the fact that if we resize the window small enough horizontally, the labels centered under each bar, and eventually the bars themselves will start running into each other.

(Note: named constants would also be helpful to map the bar colors to what they are used for, e.g., constant HEAD_TAIL_COLOR.)

The JComponent methods, getWidth() and getHeight(), which get the width and height of the component, will come in handy here. Since CoinSimComponent is a subclass of JComponent you can directly call those methods from your component object. For an example of such calls, see the CarComponent class included in the starter code (and discussed further here).

To make sure all the necessary information appears on the window and in the right place, you will also need to know the dimensions of the label you will be displaying (here we'll just use the default font size for the given graphics context). This is not covered in the textbook, so here is a code snippet:

   String label = "Hello, world!";   // suppose this is the label you want to display
   Font font = g2.getFont();
   FontRenderContext context = g2.getFontRenderContext();
   Rectangle2D labelBounds = font.getStringBounds(label, context);
   int widthOfLabel = (int) labelBounds.getWidth();
   int heightOfLabel = (int) labelBounds.getHeight();

The following diagram illustrates some of the specification for how the window should be laid out -- it is not meant to show coin-toss output, per se. (You may want to compare this with the earlier screenshots.) It will also help illustrate the meaning of the parameters to the Bar constructor.

To relate the last item to our program: scale and applicationHeight are parameters to the Bar constructor. For our program the application unit in the bar graph is a coin-toss trial.

How to communicate information between objects

There are several techniques to communicate information between classes and methods of classes, including via parameters and return values of methods. In particular, here you have the issue of receiving some information in main in CoinSimViewer, that is, the number of trials, but needing to use that information in the component. To do this, your CoinSimComponent class will need to have its own constructor (Note: this is different than the simpler component examples in the book). From main you can pass the information to that constructor, and then, if you also needed access to it in other methods, you would save it in an instance variable.

Recall that you never will be calling paintComponent yourself, nor are you allowed to change the parameters to it.


For this and all other programs you will be required to submit a text file called README with your assignment. In it you will initial the certification we mentioned earlier. This is also the place to document known bugs in your program. That means you should describe thoroughly any test cases that fail for the the program you are submitting. (Not your bug history -- just info about the version you are submitting.) You should also document here what subset your solution implements if you weren't able to complete the whole program (more about that in the next section). You can also use the README to give the grader any other special information, such as if there is some special way to compile or run your program (this would be unusual for students who complete the assignment).

For this program, also put the answers to the following questions in the README:

  1. In CS 455 what code from the web are you allowed to use in your assignment solution, assuming you modify that code once you get it? (No clue? Hint: Reread the syllabus.) Note: no need to mention the "starter files" for the assignment in your answer.

  2. What is the probability of each of the three outcomes in a trial: two heads, one head and one tail, and two tails? Why is one of them different than the other two?

  3. Roughly how many trials do you need to do before you mostly get results within 1% of these probabilities? Do several simulations using your program to determine an answer to this.

  4. Roughly how many trials can you do before it crashes with an overflow error? State the largest value you tried where it still worked correctly, and one where it overflowed. You can get an idea of what general values to try by looking at the limits on Java integers (see Section 4.1.1 of the text). Play around with your program to verify that it actually works for very large values that are within the limits. Note: this kind of testing can sometimes turn up bugs, so it's good to do. Warning: For very large values you may have to wait a fair amount of time before you get the results.

Grading criteria

This program will be graded based on correctness, style, and testing. Programs that do not compile will get little or no credit. However, an incomplete program can get some correctness points if it has partial functionality (you document the partial functionality in the README, discussed above). This grading policy is to encourage frequent testing of subsets (discussed earlier in the section on incremental development). Also, for incomplete programs, the style score will be scaled according to how much is completed.

We have published a more complete set of style guidelines for the course on the assignments page, but here are a few things to pay particular attention to for this program:

For this program only, you do not have to worry too much about method length (guideline #9), and while you should document any instance variables that are not obvious from their names, you do not have to worry about representation invariants (item #17).

Implementing the required class design and answering the README questions will also be part of your style/documentation score.

How to turn in your assignment

Make sure your name, NetID, course, assignment, and semester are at the top of each file you submit (for source files, they would be inside of comments), for any assignment you submit for this course. You will lose a point on any assignment for which this information is missing. Note: your NetID is the part of your USC email address before the @

The files you need to submit are the ones shown in bold in the earlier section on assignment files.

No matter where/how you developed the code, we will be grading it on Vocareum using the java compiler and virtual machine there (Version 1.8, aka Java 8).

If you developed your program outside of Vocareum, for example, using Eclipse on your laptop, you'll need to upload your code to Vocareum and retest it completely before you submit it. Do not wait until the final due date/time is imminent before testing it on Vocareum. Please read the earlier section on using another IDE for more details on this.

How to submit your program When you are ready to submit the assignment press the big "Submit" button in your PA1 Vocareum work area. Do not wait until the final due date/time is imminent before attempting to submit for the first time. You are allowed to submit as many times as you like, but we will only grade the last one submitted.

What happens when you click submit. Vocareum will check that you have the correct files in your work area and whether they compile. Passing these submit checks is not necessary or sufficient to submit your code (the graders will get a copy of what you submitted either way). (It would be necessary but not sufficient for getting full credit.) However, if your final submitted code does not pass all the tests we would expect that you would include some explanation of that in your README. One situation where it might fail would be if you only completed a subset of the assignment (and your README should document what subset you completed.)

The results of the submit checks will appear on your terminal window. You can also access them by going to the "Details" menu, and choosing "View Submission Report". Please read this report to see if you passed the tests, so you can fix your program and resubmit if necessary. Make sure you scroll down to the bottom of the report so you don't miss anything.

If you are unsure of whether you submitted the right version, there's a way to view the contents of your last submit in Vocareum after the fact: see the item in the file list on the left called "Latest Submission".