Question

In: Computer Science

In this assignment, you are given partial code and asked to finish the rest according to...

In this assignment, you are given partial code and asked to finish the rest according to the specified requirement.

Problem statement: one benefit of inheritance is the code reuse. Instead of writing everything from scratch, you can write a child class that reuse all the features already existed in its parent, grandparent, great grandparent, etc. In the child class, you only need to supply small amount of code that makes it unique. In the following, you are given code for two classes: Coin and TestCoin. You study these classes first and try to understand the meaning of every line. You can cut and paste the code to Eclipse and run it.

  

The following Java codes are adapted from (John Lewis and William Loftus (2007). “Software Solutions Foundations of Program Design, 5th edition”, Pearson Education, Inc. pp. 220-222).

public class Coin {

private final int HEADS = 0;

private final int TAILS = 1;

private int face;

public Coin(){

flip();

}

public void flip(){

face = (int)(Math.random()*2);

}

public boolean isHeads(){

return (face == HEADS);

}

public String toString(){

String faceName;

if(face == HEADS){

faceName = "Heads";

}else{

faceName = "Tails";

}

return faceName;

}

}

public class TestCoin {

public static void main(String[] args) {

Coin myCoin = new Coin();

myCoin.flip();

System.out.println(myCoin);

if(myCoin.isHeads()){

System.out.println("The coin has head and you win.");

}else{

System.out.println("The coin has tail and you lose.");

}

}

}

To help your understanding, I give the following brief explanation. The Coin class stores two integer constants (HEADS and TAILS) that represent the two possible states of the coin, and an instance variable called face that represents the current state of the coin. The Coin constructor initially flips the coin by calling the flip method, which determines the new state of the coin by randomly choosing a number (either 0 or 1). Since the random() method returns a random value in the range [0-1) (the left end is closed and the right end is open), the result of the expression (int)(Math.random()*2) is a random 0 or 1. The isHeads() method returns a Boolean value based on the current face value of the coin. The toString() method uses an if-else statement to determine which character string to return to describe the coin. The toString() method is automatically called when the myCoin object is passed to println() in the main method.

The TestCoin class instantiates a Coin object, flips the coin by calling the flip method in the Coin object, then uses an if-else statement to determine which of two sentences gets printed based on the result.

After running the above two classes, the following is one of the possible outputs:

Tails

The coin has tail and you lose.

Design and implement a new class MonetaryCoin that is a child of the Coin class

The new class should satisfy the following requirement. Besides all the features existed in the Coin class, the MonetaryCoin will have an extra instance variable called value to store the value of a coin. The variable value is the type of integer and has the range of 0-10. The derived class should also have an extra method getValue() that returns the value. The new class should have two constructors: one is the no-argument constructor MonetaryCoin(), the other takes one parameter aValue of integer that is used to initialize the instance variable value. According to good practice, in the body of constructor, the first line should call its super class’ no-arg constructor. To demonstrate that your new class not only has the old feature of keeping track of heads or tails but also has the new feature of keeping track of value, you should overwrite/override the method toString(). The specification for the new toString() is:

Header: String toString()

This method gives values of all instance variables as a string.

Parameters: no.

Precondition: no.

Returns: a string that takes one of the following value:

If the face is 0, value is x (here it represents an integer in the range 0..10).

The returned string should be “The coin has head and value is x.”

If the face is 1, value is x,

The returned string should be “The coin has tail and value is x.”

As a summary, this class should have four methods:

Constructor: public MonetaryCoin()

Constructor: public MonetaryCoin(int aValue)

Getter method: public int getValue()

toString method: public String toString()()

Requirements

  • Comment your code. At the top of the program include your name, a brief description of the program and what it does and the due date.
  • The program must be written in Java and submitted via D2L.
  • The code matches the class diagram given above.
  • The code uses Inheritance.

Grading

Your grade in this assignment depends on the following:

  • Your submission meets all the requirements as described above.
  • The program is robust with no runtime errors or problems; it produces outputs that

Meet the requirement.

  • You follow the good programming practices as discussed in class (check document named “codingconventions”)
  • You follow the below submission instructions.

Required Work

You are asked to the following to get points:

  1. Write the class MonetaryCoin according to the specifications outlined in the Problem Statement section (16 pts)

In order to check the correctness of your code, I give you the following driver class. You must use this driver class to get full credit.

public class TestCoin {

public static void main(String[] args) {

int totalHeads = 0;

int totalValue = 0;

MonetaryCoin mCoin = new MonetaryCoin(1);

mCoin.flip();

System.out.println(mCoin);

if(mCoin.isHeads()) {

totalHeads += 1;

}

totalValue += mCoin.getValue();

mCoin = new MonetaryCoin(10);

mCoin.flip();

System.out.println(mCoin);

if(mCoin.isHeads()) {

totalHeads += 1;

}

totalValue += mCoin.getValue();

mCoin = new MonetaryCoin(2);

mCoin.flip();

System.out.println(mCoin);

if(mCoin.isHeads()) {

totalHeads += 1;

}

totalValue += mCoin.getValue();

mCoin = new MonetaryCoin(3);

mCoin.flip();

System.out.println(mCoin);

if(mCoin.isHeads()) {

totalHeads += 1;

}

totalValue += mCoin.getValue();

System.out.println("The total heads is " + totalHeads);

System.out.println("The total value is " + totalValue);

}

}

The driver class instantiates four MonetaryCoin objects. It has two variables (totalHeads, totalValue) to keep track of the total number of heads and the accumulative value. Finally, it prints two summary information about the total heads and the total value.

2. Using UML notation, draw the class diagram in the space below (your class diagram must match your code, your class diagram should contain TestCoin, Coin, MonetaryCoin and the relationships among them) (10 pts).

SUPPLY THE CLASS DIAGRAM IN THE SPCE BELOW TO SCORE YOUR POINTS:

3. Choose one method from the MonetaryCoin class and give one paragraph of description in the space below. You can focus on one or two of the following areas: 1) functional perspective such as what the method will do; or 2) implementation perspective such as whether the method is overloaded, etc.

Solutions

Expert Solution

/********************Coin.java**********************/


/**
* The Class Coin.
*/
public class Coin {

   /** The heads. */
   private final int HEADS = 0;

   /** The tails. */
   private final int TAILS = 1;

   /** The face. */
   private int face;

   /**
   * Instantiates a new coin.
   */
   public Coin() {

       flip();

   }

   /**
   * Flip.
   */
   public void flip() {

       face = (int) (Math.random() * 2);

   }

   /**
   * Checks if is heads.
   *
   * @return true, if is heads
   */
   public boolean isHeads() {

       return (face == HEADS);

   }

   /*
   * (non-Javadoc)
   *
   * @see java.lang.Object#toString()
   */
   public String toString() {

       String faceName;

       if (face == HEADS) {

           faceName = "Heads";

       } else {

           faceName = "Tails";

       }

       return faceName;

   }

}

/*******************************MonetaryCoin.java***************************/


/**
* The Class MonetaryCoin.
*/
public class MonetaryCoin extends Coin {

   /** The value. */
   private int value;

   /**
   * Instantiates a new monetary coin.
   */
   public MonetaryCoin() {

       this.value = 0;
   }

   /**
   * Instantiates a new monetary coin.
   *
   * @param value the value
   */
   public MonetaryCoin(int value) {
       super();
       this.value = value;
   }

   /**
   * Gets the value.
   *
   * @return the value
   */
   public int getValue() {
       return value;
   }

   /*
   * (non-Javadoc)
   *
   * @see Coin#toString()
   */
   @Override
   public String toString() {
       return "The coin has " + super.toString() + " and value is " + value;
   }

}
/*************************TestCoin.java************************/


/**
* The Class TestCoin.
*/
public class TestCoin {

   /**
   * The main method.
   *
   * @param args the arguments
   */
   public static void main(String[] args) {

       int totalHeads = 0;

       int totalValue = 0;

       MonetaryCoin mCoin = new MonetaryCoin(1);

       mCoin.flip();

       System.out.println(mCoin);

       if (mCoin.isHeads()) {

           totalHeads += 1;

       }

       totalValue += mCoin.getValue();

       mCoin = new MonetaryCoin(10);

       mCoin.flip();

       System.out.println(mCoin);

       if (mCoin.isHeads()) {

           totalHeads += 1;

       }

       totalValue += mCoin.getValue();

       mCoin = new MonetaryCoin(2);

       mCoin.flip();

       System.out.println(mCoin);

       if (mCoin.isHeads()) {

           totalHeads += 1;

       }

       totalValue += mCoin.getValue();

       mCoin = new MonetaryCoin(3);

       mCoin.flip();

       System.out.println(mCoin);

       if (mCoin.isHeads()) {

           totalHeads += 1;

       }

       totalValue += mCoin.getValue();

       System.out.println("The total heads is " + totalHeads);

       System.out.println("The total value is " + totalValue);

   }

}

/*******************output*******************/

The coin has Heads and value is 1
The coin has Heads and value is 10
The coin has Tails and value is 2
The coin has Heads and value is 3
The total heads is 3
The total value is 16

Please let me know if you have any doubt or modify the answer, Thanks :)


Related Solutions

I have to finish the code given by my diff eq professor to analyze the lorenz...
I have to finish the code given by my diff eq professor to analyze the lorenz function at different initial conditions and different values for p. I am not sure how to input the lorenz function in the way the code is set up. Here is the code provided for matlab: function lorenz s = 10; b = 8/3; p = 0.15; y = @(t,x) [ ; ; ]; % you are responsible for entering the lorenz system here T...
Language for this question is Java write the code for the given assignment Given an n...
Language for this question is Java write the code for the given assignment Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order.Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n denoting the size of the matrix. Then the next line contains the n x n elements...
Throughout this course, you will be designing a Counseling Group from start to finish. The assignment...
Throughout this course, you will be designing a Counseling Group from start to finish. The assignment will be broken into four parts, which are due at different intervals in the course. For the three-part assignment, choose from the following group types (If you are in the addiction counseling program, select an addiction group) PCN-520 WEEK 2
Assignment Content Resource: ****************************CODE PASTED BELOW******************************* For this assignment, you will develop Java™ code that relies...
Assignment Content Resource: ****************************CODE PASTED BELOW******************************* For this assignment, you will develop Java™ code that relies on localization to format currencies and dates. In NetBeans, copy the linked code to a file named "Startercode.java". Read through the code carefully and replace all occurrences of "___?___" with Java™ code. Note: Refer to "Working with Dates and Times" in Ch. 5, "Dates, Strings, and Localization," in OCP: Oracle® Certified Professional Java® SE 8 Programmer II Study Guide for help. Run and debug...
Python code Assignment Overview In this assignment you will practice with conditionals and loops (for). This...
Python code Assignment Overview In this assignment you will practice with conditionals and loops (for). This assignment will give you experience on the use of the while loop and the for loop. You will use both selection (if) and repetition (while, for) in this assignment. Write a program that calculates the balance of a savings account at the end of a period of time. It should ask the user for the annual interest rate, the starting balance, and the number...
/* Assignment : Complete this javascript file according to the individual instructions given in the comments....
/* Assignment : Complete this javascript file according to the individual instructions given in the comments. */ // 1) Utilize comments to prevent the following line from executing alert('Danger!'); // 2) Assign a value of 5 to a variable named x // and print the value of x to the console // 3) Assign a value of 10 to a variable named myNum // and print the value of myNum to the console // 4) Assign the product of x...
/* Assignment: Complete this javascript file according to instructions given in the comments. */ // 1)...
/* Assignment: Complete this javascript file according to instructions given in the comments. */ // 1) Declare a variable named myName equal to your first name //Firstname is Susan // Construct a basic IF statement that prints the variable to the // console IF the length of myName is greater than 1 // 2) Copy your IF statement from above and paste it below // Change the IF statement to check if the length of myName // is greater than...
Finish one part before you proceed to the next part. Turn in your source code, the...
Finish one part before you proceed to the next part. Turn in your source code, the content of each file (including the text files) and the snapshot of the execution results for each part. Part One: Write a Python program, called myEncryption.py, which takes three inputs: (1) the name of a text file, called plain.txt, (2) a user input integer k in the range of (1-25) and (3) the name of an output file, called encrypted.txt. The program encrypts the...
This assignment provides you with an opportunity to create a code of ethics for you and...
This assignment provides you with an opportunity to create a code of ethics for you and your family, as well as to explain the strategies and thought processes that went into developing the code. First, create an original code of ethics for your family by thinking about your family as an organization. In your code of ethics, please include the following items:  guiding principles,  purpose of the code,  core values,  training and education (How will you...
Using JAVA and NETBEANS Assignment Content For this assignment, you will develop "starter" code. After you...
Using JAVA and NETBEANS Assignment Content For this assignment, you will develop "starter" code. After you finish, your code should access an existing text file that you have created, create an input stream, read the contents of the text file, sort and store the contents of the text file into an ArrayList, then write the sorted contents via an output stream to a separate output text file. Copy and paste the following Java™ code into a JAVA source file in...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT