Pages

Thursday, 25 August 2016

Chapter 7 Exercise 35, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

***7.35 (Game: hangman) Write a hangman game that randomly generates a word and prompts the user to guess one letter at a time, as shown in the sample run. Each letter in the word is displayed as an asterisk. When the user makes a correct guess, the actual letter is then displayed. When the user finishes a word, display the number of misses and ask the user whether to continue to play with another word. Declare an array to store words, as follows: // Add any words you wish in this array String[] words = {"write", "that", ...};

(Guess) Enter a letter in word ******* > p
(Guess) Enter a letter in word p****** > r
(Guess) Enter a letter in word pr**r** > p
p is already in the word
(Guess) Enter a letter in word pr**r** > o
(Guess) Enter a letter in word pro*r** > g
(Guess) Enter a letter in word progr** > n
n is not in the word
(Guess) Enter a letter in word progr** > m
(Guess) Enter a letter in word progr*m > a
The word is program. You missed 1 time
Do you want to guess another word? Enter y or n> 



import java.util.Scanner;
 
public class ProgrammingEx7_35 {
 
 public static void main(String[] args) {
  String[] words = { "write", "that", "test", "love", "hate", "happy" };
 
  Scanner input = new Scanner(System.in);
  String ans;
 
  do {
   int i = intRandom(0, words.length - 1);
   char[] word = words[i].toCharArray();
   boolean[] mask = new boolean[word.length];
   int numberOfCorrectGuess = 0;
   int numberOfMisses = 0;
   while (numberOfCorrectGuess != word.length) {
    System.out.print("(Guess) Enter a letter in word ");
 
    // Print out result
    for (int j = 0; j < word.length; j++) {
 
     if (mask[j])
      System.out.print(word[j]);
     else
      System.out.print("*");
 
    }
 
    System.out.print(">");
    char guess = input.next().charAt(0);
 
    // Checking
    boolean miss = true;
    boolean repeat = false;
 
    for (int j = 0; j < word.length; j++) {
     if (word[j] == guess) {
      if (mask[j] != true) {
       mask[j] = true;
       numberOfCorrectGuess++;
      } else {
       repeat = true;
       break;
      }
      miss = false;
     }
    }
 
    if (miss)
     numberOfMisses++;
    if (repeat)
     System.out.println(guess + " is already in the word");
 
   }
 
   System.out.println("The word is " + String.valueOf(word)
     + ". You missed " + numberOfMisses + " time");
   System.out
     .print("Do you want to guess another word? Enter y or n>");
   ans = input.next();
  } while (ans.charAt(0) != 'n');
 
 }
 
 public static int intRandom(int lowerBound, int upperBound) {
  return (int) (lowerBound + Math.random()
    * (upperBound - lowerBound + 1));
 }
 
}

2 comments: