Java

OOP GUIDE / WORK

 

HAND CLASS

 

Topics

  • Aggregation (with no encapsulation)

 

 

TASK – PART 1 – SETUP – CARD CLASS

 

Start by copying this Card class to your IDE.

 

public class Card

{

     public int value;

     public String suit;

 

     public Card(int tvalue, String tsuit)

     {

           value = tvalue;

           suit = tsuit;

     }

 

     public Card()

     {

           value = (int)(Math.random() * 13 + 1);

           double rn = Math.random();

           if (rn <= 0.25)

           {

                suit = "Hearts";

           }

           else if (rn <= 0.50)

           {

                suit = "Diamonds";

           }

           else if (rn <= 0.75)

           {

                suit = "Spades";

           }

           else

           {

                suit = "Clubs";

           }

     }

 

     public Card(String tsuit)

     {

         suit = tsuit;

         value = (int)(Math.random() * 13 + 1);

     }

 

     public String toString()

     {

         return value + " of " + suit;

     }

 

}

 

 

TASK – PART 2 – HAND CLASS

 

Create a Hand class that has the following:

  • It has five Card instance variables.  They are named c1, c2, c3, c4 and c5.
  • It has a constructor that gets five Card objects as arguments and passes them to the data fields.
  • It has a constructor that has no arguments and creates five Cards randomly (see constructors in the Card class) for the data fields.
  • It has a get method of each card.
  • It has a method named allRed() that returns true only if every card is either a heart or a diamond.
  • It has a method named allBlack() that returns true only if every card is either a spade or a club.
  • It has a method named containsPair() that returns true if there is at least a pair in the hand.
  • It has a toString() method that returns a String representation of the Hand object.

 

Test your method by creating a Hand object and trying your methods.