Java program Write a text-based program to play a game of Hangman. Your program
ID: 3688922 • Letter: J
Question
Java program
Write a text-based program to play a game of Hangman. Your program will read in a dictionary file and randomly choose a word. The user will then guess letters until they either guess the word or run out of guesses.
Use this command: java -jar Hangman.jar
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 user’s guess
if the user hasn’t already guessed that letter
check if the guess is right or wrong
if the user didn’t 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 user’s 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
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.
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.
Thank you!
Explanation / Answer
import java.util.*;
class Hangman {
static Scanner scan = new Scanner(System.in);
static Random rand = new Random();
static boolean isIn(char c, String str) {
int occurrence = str.indexOf(c);
if (occurrence >= 0)
return true;
else
return false;
}
static boolean printCurrStatus(String strToGuess, String userInputs) {
String current = "";
String positionTemp = "";
String currentTemp = "";
for (int i = 0; i < strToGuess.length(); i++) {
current += "_" + " ";
positionTemp += strToGuess.charAt(i) + " ";
}
for (int i = 0; i < userInputs.length(); i++) {
char input = userInputs.charAt(i);
if (isIn(input, strToGuess)) {
int index = 0;
int position = 0;
while (index > -1) {
index = positionTemp.indexOf(input, position);
if (index < 0)
break;
else {
currentTemp = current.substring(0, index) + input;
currentTemp += current.substring(index + 1,
positionTemp.length() - 1);
current = currentTemp;
position += 1;
}
}
}
}
System.out.println(current);
if (current.indexOf('_') < 0)
return true;
else
return false;
}
static String getNextWordToGuess() {
String[] nextWord = { "javascript", "declaration", "object", "class", "failing"};
int newRandom = rand.nextInt(nextWord.length);
return nextWord[newRandom];
}
static void playGame() {
String userInput = "";
String wordToGuess = getNextWordToGuess();
while (!printCurrStatus(wordToGuess, userInput))
{
System.out.println("Current Status for userInputs = "+userInput);
System.out.print("Enter next letter:");
userInput += scan.next();
System.out.println("");
}
}
public static void main(String[] args) {
String choice = "y";
while (choice.equals("y")) {
playGame();
System.out.println("Congratulations: you guessed the word!!");
System.out.println("Do you want to play again? (y or n)");
choice = scan.next();
}
System.out.println("Bye");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.