1. Write an application that contains an array of 10 multiple-choice quiz questions related to your favorite hobby. Each question contains three answer choices. Also create an array that holds the correct answer to each question—A, B, or C. Display each question and verify that the user enters only A, B, or C as the answer—if not, keep prompting the user until a valid response is entered. If the user responds to a question correctly, display Correct!; otherwise, display The correct answer is and the letter of the correct answer. After the user answers all the questions, display the number of correct and incorrect answers. Save the file as Quiz.java.

    import javax.swing.*; public class Quiz { public static void main(String[] args) { String[] questions = {"How many players on a basketball team?\nA. 5 B. 6 C. 7", "How many points for a basket?\nA. 1 B. 2 C. 3", "How many points for a free throw?\nA. 1 B. 2 C. 3", "You can earn three points when you\nA. Make any basket\n" + "B. Throw from inside the three-point line\n" + "C. Throw from outside the three-point line", "What is the name of Chicago's NBA team?\n" + "A. Bulls B. Bears C. Cubs", "Who may ask a referee about a rule interpretation?\n" + "A. Team captain\n" + "B. A player who receives a foul\n" + "C. Any player on the floor", "Suppose a shooter from team A makes a basket\n" + "in team B's basket. Who gets credit for the basket?\n" + "A. The player who made the basket\n" + "B. The last player from team B who made a basket\n" + "C. The player from team B nearest the shooter", "A basketball game starts with a\n" + "A. Jump ball\nB. Throw in from the side\n" + "C. Throw in from the end", "Bouncing a ball while walking is\n" + "A. Slobbering B. Dribbling C. Dabbling", "Taking steps with the ball without dribbling is called\n" + "\nA. Stepping B. Dunking C. Travelling"}; char[] answers = {'A', 'B', 'A', 'C', 'A', 'A', 'C', 'A', 'B', 'C' }; char ans = ' '; int x, correct = 0; String entry; boolean isGood; for(x = 0; x < questions.length; ++x) { isGood = false; int firstError = 0; while(!isGood) { isGood = true; entry = JOptionPane.showInputDialog(null,questions[x]); ans = entry.charAt(0); if(ans != 'A' && ans != 'B' && ans != 'C') { isGood = false; if(firstError == 0) { questions[x] = questions[x] + "\nYour answer must be A, B or C."; firstError = 1; } } } if(ans == answers[x]) { ++correct; JOptionPane.showMessageDialog(null, "Correct!"); } else JOptionPane.showMessageDialog(null, "The correct answer is " + answers[x]); } JOptionPane.showMessageDialog(null, "You got " + correct + " right and\n" +(questions.length -correct) + " wrong"); } }
    1. In Chapter 4, you created a Die application that randomly “throws” five dice for the computer and five dice for the player. The application displays the values. Modify the application to decide the winner based on the following hierarchy of Die values. Any higher combination beats a lower one—for example, five of a kind beats four of a kind. • Five of a kind • Four of a kind • Three of a kind • A pair For this game, the dice values do not count; for example, if both players have three of a kind, it’s a tie, no matter what the values of the three dice are. Additionally, the game does not recognize other poker hand type combinations such as a full house (three of a kind plus two of a kind) or a straight (sequential values). Figure 8-21 shows a sample execution. Save the application as FiveDice2.java.
      public class FiveDice2 { public static void main(String[] args) { final int NUM = 5; Die[] comp = new Die[NUM]; Die[] player = new Die[NUM]; int x; for(x = 0; x < NUM; ++x) { comp[x] = new Die(); player[x] = new Die(); } int compMatch, playerMatch; String computerName = "Computer"; String playerName = "You"; display(computerName, comp, NUM); display(playerName, player, NUM); compMatch = howManySame(comp, NUM); playerMatch = howManySame(player, NUM); if(compMatch == 1) System.out.println("Computer has nothing"); else System.out.println("Computer has " + compMatch + " of a kind"); if(playerMatch == 1) System.out.println("You have nothing"); else System.out.println("You have " + playerMatch + " of a kind"); if(compMatch > playerMatch) System.out.println("Computer wins"); else if(compMatch < playerMatch) System.out.println("You win"); else System.out.println("It's a tie"); } public static void display(String who, Die[] die, int num) { int x; String dice = ""; for(x = 0; x < num; ++x) dice = dice + die[x].getValue() + " "; System.out.println(who + " rolled: " + dice); } public static int howManySame(Die[] die, int num) { int[] same = new int[num]; int x, y; int highest; for(x = 0; x < num; ++x) same[x] = 1; // every die matches itself for(x = 0; x < num - 1; ++x) { for(y = x + 1; y < num; ++y) if(die[x].getValue() == die[y].getValue()) { same[x]++; } } highest = same[0]; for(x = 1; x < num; ++x) if(same[x] > highest) highest = same[x]; return highest; } }
    2. Improve the FiveDice2 game so that when both players have the same combination of dice, the higher value wins. For example, two 6s beats two 5s. Save the application as FiveDice3.java.

      public class FiveDice3 { public static void main(String[] args) { final int NUM = 5; Die[] comp = new Die[NUM]; Die[] player = new Die[NUM]; int x; for(x = 0; x < NUM; ++x) { comp[x] = new Die(); player[x] = new Die(); } int compMatch, playerMatch; int compHigh, playerHigh; String computerName = "Computer"; String playerName = "You"; display(computerName, comp, NUM); display(playerName, player, NUM); compMatch = howManySame(comp, NUM); playerMatch = howManySame(player, NUM); compHigh = compMatch / 10; playerHigh = playerMatch / 10; compMatch = compMatch % 10; playerMatch = playerMatch % 10; if(compMatch == 1) System.out.println("Computer has nothing"); else System.out.println("Computer has " + compMatch + " of a kind"); if(playerMatch == 1) System.out.println("You have nothing"); else System.out.println("You have " + playerMatch + " of a kind"); if(compMatch > playerMatch) System.out.println("Computer wins"); else if(compMatch < playerMatch) System.out.println("You win"); else { if(compHigh > playerHigh) System.out.println("Computer's values are higher - computer wins"); else if(compHigh < playerHigh) System.out.println("Your values are higher - you win"); else System.out.println("It's a tie"); } } public static void display(String who, Die[] die, int num) { int x; String dice = ""; for(x = 0; x < num; ++x) dice = dice + die[x].getValue() + " "; System.out.println(who + " rolled: " + dice); } public static int howManySame(Die[] die, int num) { int[] same = new int[num]; int x, y; int highest; int highValue = 0; for(x = 0; x < num; ++x) same[x] = 1; // every die matches itself for(x = 0; x < num - 1; ++x) { for(y = x + 1; y < num; ++y) if(die[x].getValue() == die[y].getValue()) { same[x]++; if(die[x].getValue() > highValue) highValue = die[x].getValue(); } } highest = same[0]; for(x = 1; x < num; ++x) if(same[x] > highest) highest = same[x]; highest = highest + 10 * highValue; return highest; } }
    1. In Chapter 7, you modified a previously created Card class so that each Card would hold the name of a suit (Spades, Hearts, Diamonds, or Clubs) as well as a value (Ace, King, Queen, Jack, or a number value). Now, create an array of 52 Card objects, assigning a different value to each Card, and display each Card. Save the application as FullDeck.java.

      public class FullDeck { public static void main(String[] args) { final int CARDS_IN_DECK = 52; Card[] card = new Card[CARDS_IN_DECK]; final int HIGH_SUIT = 4; int x; int suit, value; suit = 1; value = 1; for(x = 0; x < CARDS_IN_DECK; ++x) { card[x] = new Card(); if(suit == 1) card[x].setSuit("Spades"); else if(suit == 2) card[x].setSuit("Hearts"); else if(suit == 3) card[x].setSuit("Diamonds"); else card[x].setSuit("Clubs"); card[x].setValue(value); System.out.println(card[x].getRank() + " of " + card[x].getSuit()); ++value; if(value > card[x].HIGH_VAL) { ++suit; value = 1; } } } }
    2. In Chapter 7, you created a War2 card game that randomly selects two Card objects (one for the player and one for the computer) and declares a winner or a tie based on the card values. Now create a game that plays 26 rounds of War, dealing a full deck with no repeated cards. Some hints: • Start by creating an array of all 52 playing cards, as in Part a of this exercise. • Select a random number for the deck position of the player’s first card, and assign the card at that array position to the player. • Move every higher-positioned card in the deck “down” one to fill in the gap. In other words, if the player’s first random number is 49, select the card at position 49, move the card that was in position 50 to position 49, and move the card that was in position 51 to position 50. Only 51 cards remain in the deck after the player’s first card is dealt, so the available-card array is smaller by one. • In the same way, randomly select a card for the computer and “remove” the card from the deck. • Display the values of the player’s and computer’s cards, compare their values, and determine the winner. • When all the cards in the deck are exhausted, display a count of the number of times the player wins, the number of times the computer wins, and the number of ties. Save the game as War3.java.
      public class War3 { public static void main(String[] args) { final int CARDS_IN_DECK = 52; final int CARDS_EACH = CARDS_IN_DECK / 2; Card[] card = new Card[CARDS_IN_DECK]; Card playerCard = new Card(); Card computerCard = new Card(); createDeck(card, CARDS_IN_DECK); int x, y; int playerCardNum, computerCardNum; int playerWins = 0, computerWins = 0, ties = 0; int cardsLeft = CARDS_IN_DECK; for(x = 0; x < CARDS_EACH; ++x) { playerCardNum = ((int)(Math.random() * 100) % cardsLeft); playerCard.setSuit(card[playerCardNum].getSuit()); playerCard.setValue(card[playerCardNum].getValue()); for(y = playerCardNum; y < cardsLeft - 1; ++y) card[y] = card[y + 1]; --cardsLeft; computerCardNum = ((int)(Math.random() * 100) % cardsLeft); computerCard = new Card(); computerCard.setSuit(card[computerCardNum].getSuit()); computerCard.setValue(card[computerCardNum].getValue()); for(y = computerCardNum; y < cardsLeft -1; ++y) card[y] = card[y + 1]; --cardsLeft; System.out.println("Player has " + playerCard.getRank() + " of " + playerCard.getSuit() + " Computer has " + computerCard.getRank() + " of " + computerCard.getSuit()); if(playerCard.getValue() == computerCard.getValue()) { System.out.println(" It's a tie"); ++ties; } else if(playerCard.getValue() > computerCard.getValue()) { System.out.println(" Player wins"); ++playerWins; } else { System.out.println(" Computer wins"); ++computerWins; } } System.out.println("Final tally:"); System.out.println(" Player wins: " + playerWins); System.out.println(" Computer wins: " + computerWins); System.out.println(" Ties: " + ties); } public static void createDeck(Card[] card, int CARDS_IN_DECK) { final int HIGH_VAL = 13; final int LOW_VAL = 1; final int HIGH_SUIT = 4; int x; int suit, value; suit = 1; value = 1; for(x = 0; x < CARDS_IN_DECK; ++x) { card[x] = new Card(); if(suit == 1) card[x].setSuit("Spades"); else if(suit == 2) card[x].setSuit("Hearts"); else if(suit == 3) card[x].setSuit("Diamonds"); else card[x].setSuit("Clubs"); card[x].setValue(value); ++value; if(value > HIGH_VAL) { ++suit; value = 1; } } } }
  2. In Chapter 7, you created a Secret Phrase game similar to Hangman, in which the user guesses letters in a partially hidden phrase in an attempt to determine the complete phrase. Modify the program so that: • The phrase to be guessed is selected randomly from a list of at least 10 phrases. • The clue is presented to the user with asterisks replacing letters to be guessed but with spaces in the appropriate locations. For example, if the phrase to be guessed is No man is an island, then the user sees the following as a first clue: ** *** ** ** ****** The spaces provide valuable information as to where individual words start and end. • Make sure that when a user makes a correct guess, all the matching letters are filled in, regardless of case. Save the game as SecretPhrase2.java.
    import javax.swing.*; public class SecretPhrase2 { public static void main(String[] args) { String[] targetPhrases = {"The Wizard of Oz", "Gone With The Wind", "Casablanca", "Chicago", "Top Hat", "White Christmas", "The Sound of Music", "Guys and Dolls", "Its a Mad Mad Mad Mad World", "Defending Your Life"}; String displayPhrase = ""; String target; String buildDisplayPhrase; String prompt; String play = "Play our game - guess the phrase\n"; String enterOne = "Enter one letter\n"; String sorry = "Sorry - not in the phrase: "; String correct = "Correct! "; String userResponse; char guess; char letter; boolean found = false; int position; int oldPos = 0; int x; int random = (int) (Math.random() * 100) % targetPhrases.length; target = targetPhrases[random]; target = target.toLowerCase(); final int LEN = target.length(); x = 0; while(x < LEN) { if(target.charAt(x) == ' ') displayPhrase = displayPhrase + ' '; else displayPhrase = displayPhrase + "*"; ++x; } prompt = play + enterOne; while(displayPhrase.indexOf('*') != -1) { userResponse = JOptionPane.showInputDialog(null, prompt + displayPhrase); userResponse = userResponse.toLowerCase(); guess = userResponse.charAt(0); found = false; for(position = 0; position < LEN; ++position) { letter = target.charAt(position); if(letter == guess) { displayPhrase = displayPhrase.substring(0, position) + guess + displayPhrase.substring(position + 1, LEN); found = true; } } if(!found) { prompt = sorry + guess + '\n'; } else { prompt = correct + enterOne; } } JOptionPane.showMessageDialog(null, "Congratulations!\nThe phrase was:\n" + targetPhrases[random]); } }
  3. Magic 8 Ball is a toy developed in the 1950s and used for fortune-telling or advice-seeking. A player asks or thinks of a yes-or-no question such as, Will I be rich someday? The player then turns the ball over to see one of 20 randomly chosen responses, for example, It is certain or Very doubtful. Create a program that simulates the toy by allowing a user to type a question; the user then receives one of 20 random responses. Allow the user to keep asking questions until the user types in a sentinel value. Save the program as Magic8Ball.java.
    import java.util.*; public class Magic8Ball { public static void main(String[] args) { int num; String question; String[] phrases = {"Without a doubt", "Yes definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"}; final String QUIT = "ZZZ"; Scanner input = new Scanner(System.in); System.out.print("Enter your question or " + QUIT + " to quit >> "); question = input.nextLine(); while(!question.equals(QUIT)) { num = ((int)(Math.random() * 100) % phrases.length); System.out.println("Magic 8 ball says: " + phrases[num]); System.out.print("\nEnter another question or " + QUIT + " to quit >> "); question = input.nextLine(); } } }