Fundamental Programming Concepts
Summer 2000

Lab 5

Overview

Since you have an exam very soon, this lab will be fairly short, so long as you read the instructions carefully. This lab requires the use of:

  • Random number generation
  • Loops

 

Preliminary: Random Number Generation
This lab will require learning to generate random numbers with Java.  This is covered in LL pp.81-82.  Make sure that you understand Listing 2.9.  Page 74 explains the object creation syntax that is used in the listing.  You’ll also want to browse the documentation for the Random class.

 

Part I: CoinToss
Write a program that inputs from the user the number of times to toss a coin.  Use a loop to validate this input and make sure that it is positive.  Then, using a loop and a random number generator, simulate flipping a coin that many times.  You’ll have to decide how to represent coin tosses with random numbers.  Keep track of how many times you get heads, and how many times you get tails.  Your output should include the number and percentage of flips for heads and tails, e.g., “501 heads (50.1%), 499 tails (49.9%)”.

 

Part II: Triangles

Write a program that inputs and validates the size of a triangle (must be >= 2), and then prints the following four patterns, separately, one below the other, with that size as the height and width.  You may only use three types of print statements in producing the patterns:  

  • System.out.println();
  • System.out.print("*");
  • System.out.print(" ");

Hints:  

  • You may want to change your editor font, following the instructions at the beginning of Lab 3.

  • Use for loops.

  • The last two patterns require printing an appropriate number of spaces before the asterisks.  See Lecture 5 if you want an example of this.

  • Try writing the program for a fixed size pattern first, then modifying it to allow different sizes.

Patterns, size = 3: size = 4:
*
**
***

***
**
*

***
 **
  *

  *
 **
***
*
**
***
****

****
***
**
*

****
 ***
  **
   *

   *
  **
 ***
****

 

Submitting
You should gather the folders for both of the programs into a single folder called Lab5, then submit that entire folder via FTP.

Your folders should contain at least the following files:

  • Lab5
    • CoinToss
      • CoinToss.mcp
      • CoinToss.java
      • CS99.jar
    • Triangles
      • Triangles.mcp
      • Triangles.java
      • CS99.jar