Question: In JAVA language thank you SO MUCH Write a text-based program to play a game of Hangman. (If youre not familiar with the game, check

In JAVA language thank you SO MUCH

Write a text-based program to play a game of Hangman. (If youre not familiar with the game, check out the Wikipedia page here.) Your program will read in a dictionary file (provided) and randomly choose a word. The user will then guess letters until they either guess the word or run out of guesses.

There is a sample program you can run posted to WebAccess.

To run the program, download the JAR file and the words.txt file to the same directory.

Navigate to that directory using "cd" (change directory) in either a terminal window (on a MAC) or a command window (on a PC- type "cmd" into the start box).

Use this command: java -jar Hangman.jar

There are two parts to this project. The first is writing the game and getting it working properly. The second is adding exception handling. I strongly recommend you complete Part I before moving on to Part II.

Part I: The Game (50 points)

Your game must follow these rules:

The user gets a pre-defined maximum number of wrong guesses. (My program uses 7.)

If a user guesses the same wrong letter twice, this letter should only count once towards the maximum wrong guesses.

The game should ignore the case (upper or lower) of guesses.

If the user guesses a correct letter, all instance of that letter should be revealed.

Here are some notes to help:

Below is pseudocode for the game. You are not required to use this approach. but you might find it helpful.

read in the list of words in the dictionary file

randomly choose a word from this list

while the user still has guesses left and they have not guessed the word

print the word (displaying guessed letters and blanks for non-guessed letters)

read the users guess

if the user hasnt already guessed that letter

check if the guess is right or wrong

if the user didnt guess the word, update the guesses remaining

Break your code up into methods. Do not have the entire game in the main method.

You will likely need several instance data variables to keep track of things. Below are some recommendations. You are not required to use these.

counters: numLetters (size of the selected word), numIncorrectGuesses, numLettersGuessedCorrectly,

char[] selectedWordArray- you might find it helpful to keep the characters of the selected word in a char[]. This will allow you to loop through the array and compare each letter to the users guess.

boolean[] guessedLetter- you might find it helpful to use a boolean[] that represents whether the letter at each position has been guessed. This will be useful when printing the word to the user (as letters and blanks).

ArrayList lettersGuessed- keep track of which letters have been guessed

Hint for testing: Print out the randomly selected word you are trying to guess. This makes for much easier testing!

Again, I strongly recommend getting the game working before moving on to Part II.

Part II: Exception Handling (50 points)

Add exception handling to cover three erroneous occurrences.

Note: I realize you could write a working game that accounts for these situations without using exception handling. But, for this project, you are required to use exception handling.

Situation One: The dictionary file does not exist.

Use an existing Java exception class to deal with this.

Your program should end in this situation because the game cannot be played with a dictionary.

The program should end gracefully with a nice message- not crash with an error.

Situation Two: The user enters a guess that is not a character (like + or $)

Create your own exception type to represent this situation.

When the situation occurs, throw an object of the type you just created. Catch the exception and print a message to the user about what went wrong.

The user continues on and enters a new guess. The invalid guess does not count against the user.

Hint: check out the Character class for help with detecting this situation!

Situation Three: The user enters a guess that is longer than one character (like aa or zb)

Create your own exception type to represent this situation.

When the situation occurs, throw an object of the type you just created. Catch the exception and print a message to the user about what went wrong.

The user continues on and enters a new guess. The invalid guess does not count against the user.

Your main method should not terminate because of any of these thrown exceptions. All thrown exceptions should be caught and handled.

Extra Credit

15 points extra credit: Allow the user to play multiple games. Keep track of the number of wins, losses, and the win percentage. Print this information at the end of each game.

Submit a zip file containing your java files and the dictionary file. Include your name in the name of the zip file. If you are working in a group, submit only one assignment. Put the names of all group members in the comments of each java file.

SAMPLE PROGRAM:

----------------------

Hangman.class

import java.io.*; import java.text.NumberFormat; import java.util.*;

public class Hangman {

public Hangman() { }

public static void main(String args[]) { try { int numGames = 0; int numWins = 0; int numLosses = 0; boolean keepPlaying = true; Scanner scan = new Scanner(System.in); String fileName = "words.txt"; Scanner fileScan = new Scanner(new File(fileName)); ArrayList words = new ArrayList(); String word; for(; fileScan.hasNext(); words.add(word)) word = fileScan.next();

char playAgain; do { numGames++; int numWords = words.size(); Random generator = new Random(); int wordNum = generator.nextInt(numWords); String selectedWord = (String)words.get(wordNum); selectedWord = selectedWord.toUpperCase(); int numLetters = selectedWord.length(); letters = new char[numLetters]; guessed = new boolean[numLetters]; for(int i = 0; i < numLetters; i++) { guessed[i] = false; letters[i] = selectedWord.charAt(i); }

boolean alphabet[] = new boolean[26]; for(int i = 0; i < 26; i++) alphabet[i] = false;

ArrayList lettersGuessed = new ArrayList(); boolean wordGuessed = false; int numGuesses = 0; int numCorrect = 0; System.out.println(); do { System.out.println(printWord()); System.out.println((new StringBuilder("You have ")).append(7 - numGuesses).append(" guesses remaining.").toString()); if(lettersGuessed.size() > 0) System.out.println((new StringBuilder("You have guessed ")).append(lettersGuessed).toString()); System.out.println(); System.out.print("Guess a letter: "); try { String lineGuess = scan.nextLine(); if(lineGuess.length() > 1) throw new GuessTooLongException(); char charGuess = lineGuess.toUpperCase().charAt(0); int charGuessInt = Character.getNumericValue(charGuess) - 10; if(charGuessInt >= 26 || charGuessInt < 0) throw new ImproperGuessException(); if(alphabet[charGuessInt]) { System.out.println("You've already guessed that letter!"); } else { alphabet[charGuessInt] = true; boolean guessedALetter = false; for(int i = 0; i < numLetters; i++) if(letters[i] == charGuess) { guessed[i] = true; numCorrect++; guessedALetter = true; }

if(!guessedALetter) { numGuesses++; lettersGuessed.add(Character.valueOf(charGuess)); Collections.sort(lettersGuessed); } if(numCorrect == numLetters) wordGuessed = true; } } catch(GuessTooLongException ex) { System.out.println(ex.getMessage()); System.out.println(); } catch(ImproperGuessException ex) { System.out.println(ex.getMessage()); System.out.println(); } } while(!wordGuessed && numGuesses < 7); if(wordGuessed) { System.out.println(printWord()); System.out.println("Congratulations! You guessed it!"); numWins++; } else { System.out.println((new StringBuilder("Sorry, you did not guess it. The word was ")).append(selectedWord).toString()); numLosses++; } System.out.println(); System.out.println((new StringBuilder("Stats: ")).append(numWins).append(" Wins and ").append(numLosses).append(" Losses ").toString()); double winPercent = ((double)numWins * 1.0D) / (double)numGames; System.out.println((new StringBuilder("You have won ")).append(NumberFormat.getPercentInstance().format(winPercent)).append(" of the time.").toString()); System.out.println(); System.out.println("Play again? (y/n)"); playAgain = scan.nextLine().toUpperCase().charAt(0); } while(playAgain == 'Y'); } catch(FileNotFoundException ex) { System.out.println(ex.getMessage()); } }

private static String printWord() { String returnString = ""; for(int i = 0; i < letters.length; i++) { if(guessed[i]) returnString = (new StringBuilder(String.valueOf(returnString))).append(letters[i]).toString(); else returnString = (new StringBuilder(String.valueOf(returnString))).append("_").toString(); returnString = (new StringBuilder(String.valueOf(returnString))).append(" ").toString(); }

return returnString; }

public static final int CHAR_OFFSET = 10; public static final int MAX_GUESSES = 7; public static final String BLANK_LETTER = "_"; public static char letters[]; public static boolean guessed[]; }

======================

GuessTooLongException.class

public class GuessTooLongException extends Exception {

public GuessTooLongException() { super("Guesses must be one character only."); } }

===============

ImproperGuessException. class

public class ImproperGuessException extends Exception {

public ImproperGuessException() { super("Improper guess. Guesses must be characters only."); } }

=================

Dictionary file

I a ad ah al am an ar as at au ax ba be bi by cm co do ed eg eh el en er et ex fa ft go gu

......

zionist zippers zippier zipping zircons zithers zodiacs zombies zonally zonated zonulae zonular zonulas zoogony zoology zooming zoonomy zoopsia zootomy zouaves zoysias

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!