You are on page 1of 7

Java Lab 9

Please submit the following java programs through Blackboard: Exercises A Biased Coin Class (20 points): Inheritance, Method Overriding Painting Shapes (20 points): Inheritance, Method Overriding, Polymorphism, Abstract class Files to Turn In Coin.java BiasedCoin.java TestBiasedCoins.java Shape.java Sphere.java Rectangle.java Cylinder.java Paint.java PaintThings.java IntList.java SortedIntList.java ListTest.java

Extra Credit: A Sorted Integer List (10 points): Inheritance, array

A Biased Coin Class


1. The Coin class below models a coin with two sides can be flipped with equally likely outcome of each side. Create a new class named BiasedCoin that extends the coin class and models a biased coin (heads and tails are not equally likely outcomes of a flip). To do this, in BiasedCoin.java Add a private data member bias of type double. This data member will be a number between 0 and 1 that represents the probability the coin will be HEADS when flipped. So, if bias is 0.5, the coin is an ordinary fair coin. If bias is 0.6, the coin has probability 0.6 of coming up heads (on average, it comes up heads 60% of the time). Override the default constructor by assigning the value 0.5 to bias after the call to superclass constructor. This will make the default coin a fair one. Override flip method so that it generates a random floating point number between 0 and 1 (use Math.random() method), then assigns face a value of HEADS if the number is less than the bias; otherwise it assigns a value of TAILS. Add a second constructor with a single double parameterthat parameter will be the bias. If the parameter is valid (a number between 0 and 1 inclusive) the constructor should assign the bias data member the value of the parameter; otherwise it should assign bias a value of 0.5. Call flip method from the superclass to initialize the value of face. 2. Compile your class to make sure you have no syntax errors. 3. Write a program that uses one Coin object and two BiasedCoin objects. Read in the biases for the two BiasedCoins and instantiate those coins using the constructor with the bias as a parameter. Your program should then have a loop that flips each coin 1000 times and counts the number of times each is heads. After the loop print the number of heads for each coin. Run the program several times testing out different biases

//********************************************************* // Coin.java // Represents a coin with two sides that can be flipped. //********************************************************* public class Coin { protected final int HEADS = 0; protected final int TAILS = 1; protected int face; //----------------------------------------------------------------// Sets up the coin by flipping it initially. //----------------------------------------------------------------public Coin () { flip(); } //----------------------------------------------------------------// Flips the coin by randomly choosing a face value. //----------------------------------------------------------------public void flip () { face = (int) (Math.random() * 2); } //----------------------------------------------------------------// Returns true if the current face of the coin is heads. //----------------------------------------------------------------public boolean isHeads () { return (face == HEADS); } //----------------------------------------------------------------// Returns the current face of the coin as a string. //----------------------------------------------------------------public String toString() { String faceName; if (face == HEADS) faceName = "Heads"; else faceName = "Tails"; } } return faceName;

Painting Shapes
In this exercise you will develop a class hierarchy of shapes and write a program that computes the amount of paint needed to paint different objects. The hierarchy will consist of a parent class Shape with three derived classes - Sphere, Rectangle, and Cylinder. For the purposes of this exercise, the only attribute a shape will have is a name and the method of interest will be one that computes the area of the shape (surface area in the case of three-dimensional shapes). Do the following. 1. Write an abstract class Shape with the following properties: An instance variable shapeName of type String, shapeName should have a visibility modifier of protected A constructor with a String parameter that assigns shapeName An abstract method area() with a return type double A toString method that returns the name of the shape 2. The file Sphere.java contains a class for a sphere which is a descendant of Shape. A sphere has a radius and its area (surface area) is given by the formula 4*PI*radius^2. Define similar classes for a rectangle and a cylinder. Both the Rectangle class and the Cylinder class are descendants of the Shape class. A rectangle is defined by its length and width and its area is length times width. A cylinder is defined by a radius and height and its area (surface area) is PI*radius^2*height. Define the toString method in a way similar to that for the Sphere class. 3. The file Paint.java contains a class for a type of paint (which has a coverage and a method to compute the amount of paint needed to paint a shape). Correct the return statement in the amount method so the correct amount will be returned. Use the fact that the amount of paint needed is the area of the shape divided by the coverage for the paint. (NOTE: Leave the print statement - it is there for illustration purposes, so you can see the method operating on different types of Shape objects.) 4. The file PaintThings.java contains a program that computes the amount of paint needed to paint various shapes. A paint object has been instantiated. Add the following to complete the program: Instantiate the three shape objects: deck to be a 20 by 35 foot rectangle, bigBall to be a sphere of radius 15, and tank to be a cylinder of radius 10 and height 30. Make the appropriate method calls to assign the correct values to the three amount variables. Run the program and test it. You should see polymorphism in action as the amount method computes the amount of paint for various shapes.

//***************************************** // Sphere.java // // Represents a sphere. //***************************************** public class Sphere extends Shape {

{ }

private double radius; //radius in feet //---------------------------------// Constructor: Sets up the sphere. //---------------------------------public Sphere(double radius) { super("Sphere"); this.radius = radius; } //----------------------------------------// Returns the surface area of the sphere. //----------------------------------------public double area() } return 4*Math.PI*radius*radius;

//***************************************************** // Paint.java // // Represents a type of paint that has a fixed area // covered by a gallon. All measurements are in feet. // ***************************************************** public class Paint { private double coverage; //number of square feet per gallon //----------------------------------------// Constructor: Sets up the paint object. //----------------------------------------public Paint(double coverage) { this.coverage = coverage; } //--------------------------------------------------// Returns the amount of paint (number of gallons) // needed to paint the shape given as the parameter. //--------------------------------------------------public double amount(Shape s) { System.out.println ("Computing amount for " + s); return 0; } } //*********************************************************** // PaintThings.java // // Computes the amount of paint needed to paint various // things. Uses the amount method of the paint class which // takes any Shape as a parameter. //*********************************************************** import java.text.DecimalFormat; public class PaintThings {

//----------------------------------------// Creates some shapes and a Paint object // and prints the amount of paint needed // to paint each shape. //----------------------------------------public static void main (String[] args) { final double COVERAGE = 350; Paint paint = new Paint(COVERAGE); Rectangle deck; Sphere bigBall; Cylinder tank; double deckAmt, ballAmt, tankAmt; // Instantiate the three shapes to paint

// Compute the amount of paint needed for each shape

// Print the amount of paint for each. DecimalFormat fmt = new DecimalFormat("0.#"); System.out.println ("\nNumber of gallons of paint needed..."); System.out.println ("Deck " + fmt.format(deckAmt)); System.out.println ("Big Ball " + fmt.format(ballAmt)); System.out.println ("Tank " + fmt.format(tankAmt)); } }

Extra Credit: A Sorted Integer List


File IntList.java contains code for an integer list class. Save it to your directory and study it; notice that the only things you can do are create a list of a fixed size and add an element to a list. If the list is already full, a message will be printed. File ListTest.java contains code for a class that creates an IntList, puts some values in it, and prints it. Save this to your directory and compile and run it to see how it works. Now write a class SortedIntList that extends IntList. SortedIntList should be just like IntList except that its elements should always be in sorted order from smallest to largest. This means that when an element is inserted into a SortedIntList it should be put into its sorted place, not just at the end of the array. To do this you'll need to do two things when you add a new element: Walk down the array until you find the place where the new element should go. Since the list is already sorted you can just keep looking at elements until you find one that is at least as big as the one to be inserted. Move down every element that will go after the new element, that is, everything from the one you stop on to the end. This creates a slot in which you can put the new element. Be careful about the order in

which you move them or you'll overwrite your data! Now you can insert the new element in the location you originally stopped on. All of this will go into your add method, which will override the add method for the IntList class. (Be sure to also check to see if you need to expand the array, just as in the IntList add method.) What other methods/constructor, if any, do you need to override? To test your class, modify ListTest.java so that after it creates and prints the IntList, it creates and prints a SortedIntList containing the same elements (inserted in the same order). When the list is printed, they should come out in sorted order.

// An (unsorted) integer list class with a method to add an // integer to the list and a toString method that returns the contents // of the list with indices. // // **************************************************************** public class IntList { protected int[] list; protected int numElements = 0; //------------------------------------------------------------// Constructor -- creates an integer list of a given size. //------------------------------------------------------------public IntList(int size) { list = new int[size]; } //-----------------------------------------------------------// Adds an integer to the list. If the list is full, // prints a message and does nothing. //-----------------------------------------------------------public void add(int value) { if (numElements == list.length) System.out.println("Can't add, list is full"); else { list[numElements] = value; numElements++; } } //------------------------------------------------------------// Returns a string containing the elements of the list with their // indices. //------------------------------------------------------------public String toString() { String returnString = ""; for (int i=0; i<numElements; i++) returnString += i + ": " + list[i] + "\n"; return returnString; } }

// *************************************************************** // ListTest.java // // A simple test program that creates an IntList, puts some // ints in it, and prints the list. // // *************************************************************** public class ListTest { public static void main(String[] args) { IntList myList = new SortedIntList(10); myList.add(84); myList.add(27); myList.add(250); myList.add(18); myList.add(94); myList.add(8); myList.add(87); System.out.println(myList); } }

You might also like