Java

OOP GUIDE / WORK

 

CARD CLASS 2

 

Topics

  • Instance variables
  • Constructors
  • Instance methods

 

 

TASK – PART 1 – CARD CLASS SETUP


You will be creating a Card class that will represent a playing card like the ones in the image below.

 

Giant Playing Cards | Olympic Party Hire

 

 

You will start with the Card class that was created in the first Card class task.  If you wish, you can go back to that task and do that one first. 

 

Copy and paste the following Card class into your IDE.

 

public class Card

{

     public int value;

     public String suit;

    

     public Card (int v, String s)

     {

           value = v;

           suit = s;

     }

    

     public Card()

     {

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

           int rn = (int)(Math.random() * 4);

           if (rn == 0)

                suit = "hearts";

           else if (rn == 1)

                suit = "diamonds";

           else if (rn == 2)

                suit = "spades";

           else

                suit = "clubs";

     }

}

 

 

TASK – PART 2 – CARD CLASS SETUP

 

Add the following methods to it:

 

          public boolean isHeart()

Returns true if the card is a heart.

 

          public boolean isDiamond()

                    Returns true if the card is a diamond.

 

          public boolean isSpade()

                    Returns true if the card is a spade.

 

          public boolean isClub()

                    Returns true if the card is a club.

 

          public boolean isFaceCard()

                    Returns true if the card is a face card.  Note that values 11, 12 and 13 are face                               cards.

 

          public String toString()

Returns a String representation of the object.  For example, if the card is a 2 of hearts, it should return “2 of H”.  If the card is a face card or an ace, this method should return the appropriate letter for the card.  For example, a king of diamonds should be “K of D” and not “13 of D”.

 

 

TASK – PART 3 – TESTING THE CARD CLASS


Create a CardTester class.  Add a main function.  Inside it, create a few Card instances and test all methods.