In: Computer Science
(a) Create a Card class that represents a playing card. It should have an int instance variable named rank and a char variable named suit. Include the following methods:
(b) Write a driver program that creates four Card objects, where c1 is initialized to 2 and ‘d’, c2 is a copy of c1, c3 is initialized with user’s input, and c4 is set to null. Demonstrate all the capabilities and methods of the Card class and generate the following output.
~/cs1400/2020fall/exam $ java CardTest
card1 is (diamonds, 2)
card2 is (diamonds, 2)
creating card3...
enter rank(1-13): 8
enter suit(d=diamonds, h=hearts, s=spades, c=clubs): c
card3 is (clubs, 8)
set card4 to null
card1==card2? true
card1==card3? false
card1==card4? false
Program Code Screenshot (Card.java)
Program Code Screenshot (CardTest.java)
Program Sample Input/Output Screenshot
Program Code to Copy (Card.java)
import java.util.Scanner;
public class Card {
// instance variables
private int rank;
private char suit;
// getters and setters
public int getRank() {
return this.rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public char getSuit() {
return this.suit;
}
public void setSuit(char suit) {
this.suit = suit;
}
// constructor
public Card(int r, char s) {
rank = r;
suit = s;
}
// copy constructor
public Card(Card other) {
rank = other.getRank();
suit = other.getSuit();
}
// equals method
public boolean equals(Card other) {
if(other==null)
return false;
return rank == other.rank && suit == other.suit;
}
// toString method
public String toString() {
switch (suit) {
case 'd':
return "(diamonds, " + rank + ")";
case 'h':
return "(hearts, " + rank + ")";
case 's':
return "(spades, " + rank + ")";
case 'c':
return "(clubs, " + rank + ")";
}
return "";
}
// A static method read which reads rank and suit from the user, and returns an
// object of type Card.
public static Card create() {
int rank;
char suit;
Scanner sc = new Scanner(System.in);
System.out.print("enter rank(1-13): ");
rank = sc.nextInt();
System.out.print("enter suit(d=diamonds, h=hearts, s=spades, c=clubs): ");
suit = sc.next().charAt(0);
// create object and return
return new Card(rank, suit);
}
}
Program Code to Copy (CardTest.java)
public class CardTest {
// Write a driver program that creates four Card objects
public static void main(String[] args) throws Exception {
// c1 is initialized to 2 and ‘d’
Card c1 = new Card(2, 'd');
// Print card 1
System.out.println("card1 is "+c1);
// c2 is a copy of c1
Card c2 = new Card(c1);
// Print card 2
System.out.println("card2 is "+c2);
// c3 is initialized with user’s input
Card c3 = Card.create();
// Print card 3
System.out.println("card3 is "+c3);
// c4 is set to null.
System.out.println("set card4 to null");
Card c4 = null;
// Demonstrate all the capabilities and methods of the Card class
System.out.println("card1==card2? "+c1.equals(c2));
System.out.println("card1==card3? "+c1.equals(c3));
System.out.println("card1==card4? "+c1.equals(c4));
}
}