Question

Comment your code. At the top of the program include your name, a brief description of...

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

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

0 0
Add a comment Improve this question Transcribed image text
Answer #1
package HomeworkLib1;

public class MonetaryCoin extends Coin{
        private int value;
        MonetaryCoin(){
                super();
                this.value = 0;
        }
        MonetaryCoin(int aValue){
                super();
                if(aValue>=0 && aValue<=10)
                        this.value= aValue;
        }
        public int getValue() {
                return this.value;
        }
        public String toString() {
                String str="";
                if(this.isHeads()) {
                        str += str + "The coin has head and the value is " + this.getValue();
                }
                else
                        str += str + "The coin has tail and the value is " + this.getValue();
                return str;
        }
}
package HomeworkLib1;

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.");
                      }
                      MonetaryCoin mc = new MonetaryCoin();
                      mc.flip();
                      System.out.println(mc);
                      mc = new MonetaryCoin(5);
                      mc.flip();
                      System.out.println(mc);
                      mc.flip();
                      mc.flip();
                      System.out.println(mc);
    }

}

Add a comment
Know the answer?
Add Answer to:
Comment your code. At the top of the program include your name, a brief description of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Step 1: Declare a base class called Coin that contains a Boolean data element called face,...

    Step 1: Declare a base class called Coin that contains a Boolean data element called face, and a random generator to fill the face element with a Boolean value (true or false). True = heads, false = tails. The class needs a default constructor, a method to flip the coin, a method to return the face element, and a toString to display “Heads” if the face is true and “Tails” if not. Step 2: Declare a subclass of Coin that...

  • # JAVA Problem Toss Simulator Create a coin toss simulation program. The simulation program should toss...

    # JAVA Problem Toss Simulator Create a coin toss simulation program. The simulation program should toss coin randomly and track the count of heads or tails. You need to write a program that can perform following operations: a. Toss a coin randomly. b. Track the count of heads or tails. c. Display the results. Design and Test Let's decide what classes, methods and variables will be required in this task and their significance: Write a class called Coin. The Coin...

  • Here is a sample run of the tester program: Make sure your program follows the Java...

    Here is a sample run of the tester program: Make sure your program follows the Java Coding Guidelines. Consider the following class: /** * A store superclass with a Name and Sales Tax Rate */ public class Store {      public final double SALES_TAX_RATE = 0.06;      private String name;           /**      * Constructor to create a new store      * @param newName      */      public Store(String newName)      {           name = newName;      }     ...

  • import java.util.Scanner; public class Client{ public static void main(String args[]){    Coin quarter = new Coin(25);...

    import java.util.Scanner; public class Client{ public static void main(String args[]){    Coin quarter = new Coin(25); Coin dime = new Coin(10); Coin nickel = new Coin(5);    Scanner keyboard = new Scanner(System.in);    int i = 0; int total = 0;    while(true){    i++; System.out.println("Round " + i + ": "); quarter.toss(); System.out.println("Quarter is " + quarter.getSideUp()); if(quarter.getSideUp() == "HEADS") total = total + quarter.getValue();    dime.toss(); System.out.println("Dime is " + dime.getSideUp()); if(dime.getSideUp() == "HEADS") total = total +...

  • This is the code I have written for a BingoBall program, I'd appreciate it if someone...

    This is the code I have written for a BingoBall program, I'd appreciate it if someone could help me fix this public class BingoBall { private char letter; private int number; // NOTE TO STUDENT // We challenge you to use this constant array as a lookup table to convert a number // value to its appropriate letter. // HINT: It can be done with with a single expression that converts the number // to an index position in the...

  • Java Homework Help. Can someone please fix my code and have my program compile correctly? Thanks...

    Java Homework Help. Can someone please fix my code and have my program compile correctly? Thanks for the help. Specifications: The class should have an int field named monthNumber that holds the number of the month. For example, January would be 1, February would be 2, and so forth. In addition, provide the following methods. A no- arg constructor that sets the monthNumber field to 1. A constructor that accepts the number of the month as an argument. It should...

  • The following code must be written and run with no errors in java eclipse Description of...

    The following code must be written and run with no errors in java eclipse Description of the code to be written: A resistor is an electronic part colour-coded with three coloured bands to indicate its resistance value. This program returns the resistance of a Resistor object instantiated with three Strings, representing the three colour bands of a real resistor. Start by creating an abstract class 'AbstractResistor' that implements the Comparable interface. This class should have the following three private methods:...

  • In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program...

    In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program to create a database of dogs of your own. You will also include File I/O with this program. You will create 3 classes for this assignment. The first class: Create a Class representing the information that is associated with one item (one dog) of your database. Name this class Dog. Using Lab 3, this will include the information in regard to one dog. The...

  • PLEASE DO IN C# AND MAKE SURE I CAN COPY CODE IN VISUAL STUDIO Program 2:...

    PLEASE DO IN C# AND MAKE SURE I CAN COPY CODE IN VISUAL STUDIO Program 2: Design (pseudocode) and implement (source code) a class called Counter. It should have one private instance variable representing the value of the counter. It should have two instance methods: increment() which adds on to the counter value and getValue() which returns the current value. After creating the Counter class, create a program that simulates tossing a coin 100 times using two Counter objects (Head...

  • Hello. I need help writing the following Java Program. Thank you Develop a class encapsulating the...

    Hello. I need help writing the following Java Program. Thank you Develop a class encapsulating the concept of a college course, assuming that a course has following attributers: code (for instance COSC1337), a description, and a number of credits (for instance 3). Include a constructor, the accessors, mutators and methods ‘toString’, ‘equals’, and ‘finalize’. Write a client class to test the behavior of the class and its methods. The outline of the class is given as follows: public class Course...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT