1. Homepage
  2. Programming
  3. CS 455 Programming Assignment 1: Coin Toss Simulation

CS 455 Programming Assignment 1: Coin Toss Simulation

Engage in a Conversation
USUSCUniversity of Southern CaliforniaCS 455CS455CSCI 455CSCI455Introduction to Programming Systems DesignjavaCoin Toss Simulation

CS 455 Programming Assignment 1

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

Introduction

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. CourseNana.COM

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: 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). CourseNana.COM

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: CourseNana.COM

Resources

  • Horstmann, Section 2.9, 2.10, 3.8, How-to 3.2 Programs that draw stuff
  • Horstmann, Chapter 3, Implementing Classes
  • Horstmann, Section 4.3.1, Reading input
  • Horstmann, Section 6.9.1, Random numbers and Simulations

The programming environment for this assignment

Reminder: The first time you access the assignment on Vocareum, (More detailed directions about this were given on ). 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. CourseNana.COM

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. CourseNana.COM

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". CourseNana.COM

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 CourseNana.COM

cd
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 Linux 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: CourseNana.COM

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

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. CourseNana.COM

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. CourseNana.COM

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. CourseNana.COM

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. CourseNana.COM

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

  1. Install and try out another IDE. There are a few tutorials in the Java section of the 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 submitting the correct version of your solution.
  6. Submit your assignment on Vocareum

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. CourseNana.COM

CourseNana.COM

  • CarViewer.javaCarComponent.java, and Car.java. The code for the example in Section 3.8 of the textbook. 
  • CoinTossSimulator.java Your CoinTossSimulator class. The public interface is provided. You will be completing the implementation and a test driver for it.
  • Bar.java A Bar class. The public interface is provided. You will be completing the implementation of it.
  • CoinSimViewer.java Your CoinSimViewer class. You create this file and class.
  • CoinSimComponent.java Your CoinSimComponent class. You create this file and class.
  • CoinTossSimulatorTester.java Your unit test program (a.k.a., test driver) for your CoinTossSimulator class. You create this file and class.
  • CoinSimViewer.list A list of the .java files for compiling the CoinSimViewer program. 
  • Before you start the assignment please read the following statement which you will be "signing" in the README:
    "I certify that the work submitted for this assignment does not violate USC's student conduct code. In particular, the work is my own, not a collaboration, and does not involve code created by other people, with the exception of the resources explicitly mentioned in the CS 455 Course Syllabus. And I did not share my solution or parts of it with other students in the course."

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.  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. CourseNana.COM

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

1000
  trials output CourseNana.COM

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%. CourseNana.COM

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. CourseNana.COM

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 user dragged the corner to resize the window: CourseNana.COM

CourseNana.COM

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

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) CourseNana.COM

CourseNana.COM

More details of the error-checking
CourseNana.COM

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.)

CourseNana.COM

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).

You can use the code in CarViewer as a starting point for your CoinSimViewer class for this assignment. CourseNana.COM

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). CourseNana.COM

CourseNana.COM

We also modified CarComponent.java a little bit from the version of the code from the text: we instrumented the code so it prints a message to the console 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. CourseNana.COM


You are required to use the following classes (ones in bold are ones you will be creating yourself or implementing):
  • CoinSimViewer. Contains the main method. Prompts for the number of trials, and creates the JFrame containing the CoinSimComponent. Besides CoinSimComponent, this class does not depend on any of the other classes mentioned here (e.g., if one of those other classes changed, CoinSimViewer would not have to change.) The later section on communicating information between objects will be useful when developing this and the next class listed.

    CourseNana.COM

  • CoinSimComponent. Extends JComponent. Constructor initializes any necessary data and runs the simulation. Overrides paintComponent to draw the bar graph, using Bar objects for each bar in the graph. This class uses the CoinTossSimulator and Bar class.

    CourseNana.COM

  • CoinTossSimulator. This is the class responsible for doing the simulation. It has no graphical output, and in fact, does no I/O to the console either. It has a run method to run a simulation of tossing a pair of coins for some number of trials. It has accessors to get the results of the simulation. Subsequent calls to run add trials to the current simulation. To reset the CoinTossSimulator to start a new simulation

    We are giving you the exact interface to use for this class. By interface, we mean what clients need to know about the class to use it, i.e., the class comment, the method headers and associated method comments. Do not change the interface when you incorporate it into your own program. For all assignments in this class, when we say that, we mean no changing the provided method headers, no adding public methods, no removing public methods. As part of the grading process, we will be using our own test programs with such classes, and if you change the public interface your code might not even compile with our test programs. CourseNana.COM

    CoinTossSimulator does not depend on any of the other of your classes or the graphics library. It does use Random (described further below). The skeleton code for CoinTossSimulator is in CoinTossSimulator.java. CourseNana.COM

    CourseNana.COM

  • Bar. For drawing a bar in a bar graph. You specify the location, dimensions and color of the bar in the constructor. The only other method is draw which draws the bar given. We are giving you the exact interface for this class. (See the CoinTossSimulator bullet point for more details about what we mean by that.) Bar does not depend on any of the other of your classes, but does use the graphics library. The skeleton code for Bar is in Bar.java.

    CourseNana.COM

  • java.util.Random. The java random number generator. See section 6.9 of the textbook for examples of its use. One thing to note about Random: it's a class that through a sequence of method calls generates a sequence of values that depend on the internal state of the object (in this way it is similar to Scanner). Students often want to create a new Random object every time they want a new random number. Don't do that. Instead, normally you create one Random object in your program, and then whenever you want a new random number you make another call to nextInt on that same object. (If you create a Random object every time you are not generating a pseudo-random sequence, although it will appear that you are.)
  • To reflect what would be going on in the real-world version of these trials, your program must generate one random number to simulate a single coin toss. CourseNana.COM

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.

CourseNana.COM

Incremental development and unit testing

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.) CourseNana.COM

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. CourseNana.COM

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. CourseNana.COM

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. CourseNana.COM

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. CourseNana.COM

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. CourseNana.COM

CourseNana.COM

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.  First, here's more information about compiling Java code:

CourseNana.COM


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: CourseNana.COM

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: CourseNana.COM

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.

CourseNana.COM


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. CourseNana.COM

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.) CourseNana.COM

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

  • exp below means expected results. These are meant to be computed a different way than the actual results (i.e., you would not call getNumTrials() for the value).
  • the part in italics is not the literal output you should produce, but describes what we left out here. The parts in red are parts we would like you to pay particular attention to here -- your output will not appear in red.)
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. CourseNana.COM

CourseNana.COM

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. 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; 

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 . 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. CourseNana.COM

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

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  CourseNana.COM

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: CourseNana.COM

   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 It will also help illustrate the meaning of the parameters to the Bar constructor.
CourseNana.COM

  • x bars are evenly spaced: center of middle bar is centered in window. Depends on the window size.
  • bw bar width. This is a fixed value in the program.
  • vb vertical buffer. This is a fixed value in the program. Tallest bar means the tallest possible bar you could draw (i.e., for this program, if all the trials came out the same way).
  • label1, label2, etc. labels on a bar. These are centered under each bar.
  • s (s is for scale) one application unit in pixels. So, the bar on the right is five application-units high (applicationHeight is 5) The scale depends on window size.

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. CourseNana.COM

CourseNana.COM

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. list on the left called "Latest Submission". CourseNana.COM

CourseNana.COM


Get in Touch with Our Experts

WeChat WeChat
Whatsapp WhatsApp
US代写,USC代写,University of Southern California代写,CS 455代写,CS455代写,CSCI 455代写,CSCI455代写,Introduction to Programming Systems Design代写,java代写,Coin Toss Simulation代写,US代编,USC代编,University of Southern California代编,CS 455代编,CS455代编,CSCI 455代编,CSCI455代编,Introduction to Programming Systems Design代编,java代编,Coin Toss Simulation代编,US代考,USC代考,University of Southern California代考,CS 455代考,CS455代考,CSCI 455代考,CSCI455代考,Introduction to Programming Systems Design代考,java代考,Coin Toss Simulation代考,UShelp,USChelp,University of Southern Californiahelp,CS 455help,CS455help,CSCI 455help,CSCI455help,Introduction to Programming Systems Designhelp,javahelp,Coin Toss Simulationhelp,US作业代写,USC作业代写,University of Southern California作业代写,CS 455作业代写,CS455作业代写,CSCI 455作业代写,CSCI455作业代写,Introduction to Programming Systems Design作业代写,java作业代写,Coin Toss Simulation作业代写,US编程代写,USC编程代写,University of Southern California编程代写,CS 455编程代写,CS455编程代写,CSCI 455编程代写,CSCI455编程代写,Introduction to Programming Systems Design编程代写,java编程代写,Coin Toss Simulation编程代写,USprogramming help,USCprogramming help,University of Southern Californiaprogramming help,CS 455programming help,CS455programming help,CSCI 455programming help,CSCI455programming help,Introduction to Programming Systems Designprogramming help,javaprogramming help,Coin Toss Simulationprogramming help,USassignment help,USCassignment help,University of Southern Californiaassignment help,CS 455assignment help,CS455assignment help,CSCI 455assignment help,CSCI455assignment help,Introduction to Programming Systems Designassignment help,javaassignment help,Coin Toss Simulationassignment help,USsolution,USCsolution,University of Southern Californiasolution,CS 455solution,CS455solution,CSCI 455solution,CSCI455solution,Introduction to Programming Systems Designsolution,javasolution,Coin Toss Simulationsolution,