JAVA Playing cards are used in many computer games including
JAVA:
Playing cards are used in many computer games, including versions of such classics as solitaire, hearts, and poker. Design a Card class that contains a character data field to hold a suit (s for spades, h for hearts, d for diamonds, or c for clubs) and an integer data field for a value from 1 to 13. Include get and set methods for each field. Save the class as Card.java.
Then:
Write an application that randomly selects two playing cards and displays their values. Simply assign a suit to each of the cards, but generate a random number for each card’s value. Copy the following statements to generate a random number between 1 and 13 and assign it to a variable: final int CARDS_IN_SUIT = 13; myValue = ((int)(Math.random() * 100) % CARDS_IN_SUIT + 1);
. Save the application as PickTwoCards.java.
Solution
// Card.java
public class Card
{
private char suit;
private int number;
// getter for card number
public int getNumber()
{
return number;
}
// getter for card suit
public char getSuit()
{
return suit;
}
// setter for card number
public void setNumber(int number)
{
this.number = number;
}
// setter for card suit
public void setSuit(char suit)
{
this.suit = suit;
}
}
// PickTwoCards.java
public class PickTwoCards
{
public static void main(String[] args)
{
final int CARDS_IN_SUIT = 13;
int value1 = ((int)(Math.random() * 100) % CARDS_IN_SUIT + 1);
int value2 = ((int)(Math.random() * 100) % CARDS_IN_SUIT + 1);
Card c1 = new Card();
c1.setNumber(value1);
c1.setSuit(\'s\');
Card c2 = new Card();
c2.setNumber(value2);
c2.setSuit(\'d\');
System.out.println(\"First card => Suit: \"+ c1.getSuit() + \" Number: \" + c1.getNumber());
System.out.println(\"Second card => Suit: \"+ c2.getSuit() + \" Number: \" + c2.getNumber());
}
}
/*
output:
First card => Suit: s Number: 1
Second card => Suit: d Number: 8
*/

