b. In Chapter 5, you created a War Card game that randomly selects two cards (on
ID: 3726640 • Letter: B
Question
b. In Chapter 5, you created a War Card game that randomly selects two cards (one for the player and one for the computer) and declares a winner (or a tie). Modi the game to set each Card's suit as the appropriate string, then execute the game using the newly modified Card class. Figure 7-18 shows four typical executions. Recall that in this version of War, you assume that the Ace is the lowest-valued card. Save the game as War2.java Command Prompt :Java>java Mar2 y card is the 10 of Dianonds our card is the Queen of Hearts ou win :Java)java Mar2 y card is the Ace of Dianonds our card is the7 of Clubs ou wi :Java >java Mar2 y card is the 18 of Hearts our card is the 18 of Spades It's a tie :Java >java uar2 y card is the 9 of Dianonds our card is the 3 of Dianonds I win Figure 7-18 Four typical executions of the War2 game
Explanation / Answer
public class Card {
String suit;
int value;
public String getSuit() {
return suit;
}
public void setSuit(String suit) {
this.suit = suit;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public class War2 {
final static int NUMBER_OF_CARDS_IN_SUIT = 13;
final static int NUMBER_OF_SUITS = 4;
public static void main(String[] args) {
Card myCard = new Card();
selectCard(myCard);
Card yourCard = new Card();
selectCard(yourCard);
System.out.println("My card is the " + getCardValueText(myCard.getValue()) + " of " + myCard.getSuit());
System.out.println("Your card is the " + getCardValueText(yourCard.getValue()) + " of " + yourCard.getSuit());
if (myCard.getValue() > yourCard.getValue()) {
System.out.println("I win");
} else if (myCard.getValue() < yourCard.getValue()) {
System.out.println("You win");
} else {
System.out.println("It's a tie");
}
}
private static String getCardValueText(int value) {
switch (value) {
case 1:
return "Ace";
case 11:
return "Jack";
case 12:
return "Queen";
case 13:
return "King";
}
return String.valueOf(value);
}
private static void selectCard(Card card) {
// generate random number in between 1-4
int suitSelected = (int) (Math.random() * NUMBER_OF_SUITS + 1);
String suitText = null;
switch (suitSelected) {
case 1:
suitText = "Spades";
break;
case 2:
suitText = "Hearts";
break;
case 3:
suitText = "Diamonds";
break;
case 4:
suitText = "Clubs";
break;
}
// generate random number in between 1-13
int cardSelected = (int) (Math.random() * NUMBER_OF_CARDS_IN_SUIT + 1);
card.setSuit(suitText);
card.setValue(cardSelected);
}
}
/* OUTPUT:
My card is the 10 of Diamonds
Your card is the 5 of Spades
I win
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.