Question

For this lab you will write a Java program that plays a simple Guess The Word...

For this lab you will write a Java program that plays a simple Guess The Word game. The program will prompt the user to enter the name of a file containing a list of words. These words mustbe stored in an ArrayList, and the program will not know how many words are in the file before it starts putting them in the list. When all of the words have been read from the file, the program randomly chooses one word from the list to be the target of the game. The user is then allowed to guess characters one at a time. The program checks to see if the user has previously guessed that character and if it has been previously guessed the program forces the user to guess another character. Otherwise it checks the word to see if that character is part of the target word. If it is, it reveals all of the positions with that target word. The program then asks the user to guess the target, keeping count of the number of guesses. When the user finally guesses the correct word, the program indicates how many guesses it took the user to get it right.

For this assignment you must start with the following "skeleton" of Java code. Import this into your Eclipse workspace and fill in the methods as directed. In addition, for this assignment you MUST add at least one extra method beyond the methods defined in the skeleton. This must be a method that does something useful - if you are stuck for an idea for a method, get the program working first and then see if there is some part of your main method that you can break out to be its own function or procedure instead.

Feel free to add any additional methods you find useful, but for all of the methods you add you must also add comments indicating what they do following the form of the rest of the comments in the code.

No break statements allowed

/**
 * Your description here
 * @author ENTER YOUR NAME HERE
 * @version ENTER DATE HERE
 *
 */
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

public class WordGuessing {

    /**
     * Takes a filename as input. Reads a list of words from the file into a
     * list and returns the list. Ensures that all of the words in the list are
     * in UPPERCASE (i.e. transforms lowercase letters to uppercase before
     * adding them to the list). Assumes that the file will be correctly
     * formatted with one word per line. If the file cannot be read prints the
     * error message "ERROR: File fname not found!" where "fname" is the name of
     * the file and returns an empty list.  Note that the order of the words in the
     * list must be the same as the order of the words in the file to pass the
     * test cases.
     *
     * @param fname
     *            the name of the file to read words from
     * @return a list of words read from the file in all uppercase letters.
     */
    public static List readWords(String fname) {
        List words = new ArrayList();
        // TODO - complete this function

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return words;
    }

    /**
     * Takes a Random object and a list of strings and returns a random String
     * from the list. Note that this method must not change the list.  The list
     * is guaranteed to have one or more elements in it.
     *
     * @param rnd
     *            Random number generator object
     * @param inList
     *            list of strings to choose from
     * @return an element from a random position in the list
     */
    public static String getRandomWord(Random rnd, List inList) {
        // TODO - complete this function

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return null;
    }

    /**
     * Given a String, returns a StringBuilder object that is the same length
     * but is only '*' characters. For example, given the String DOG as input
     * returns a StringBuilder object containing "***".
     *
     * @param inWord
     *            The String to be starred
     * @return a StringBuilder with the same length as inWord, but all stars
     */
    public static StringBuilder starWord(String inWord) {
        // TODO - complete this function

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return null;
    }

    /**
     * Prompts the user to enter a single character. If the user enters a blank
     * line or more than one character, give an error message as given in the
     * assignment and prompt them again. When the user enters a single
     * character, return the uppercase value of the character they typed.
     *
     * @param inScanner
     *            A scanner to take user input from
     * @return the uppercase value of the character typed by the user.
     */
    public static char getCharacterGuess(Scanner inScanner) {
        // TODO - complete this function

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return 0;
    }

    /**
     * Count the number of times the character ch appears in the String word.
     *
     * @param ch
     *            character to count.
     * @param word
     *            String to examine for the character ch.
     * @return a count of the number of times the character ch appears in the
     *         String word
     */
    public static int charCount(char ch, String word) {
        // TODO - complete this function

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return 0;
    }

    /**
     * Modify the StringBuilder object starWord everywhere the char ch appears
     * in the String word. For example, if ch is 'G', word is "GEOLOGY", and
     * starWord is "**O*O*Y", then this method modifies starWord to be
     * "G*O*OGY".  Your code should assume that word and starWord are
     * the same length.
     *
     * @param ch
     *            the character to look for in word.
     * @param word
     *            the String containing the full word.
     * @param starWord
     *            the StringBuilder containing the full word masked by stars.
     */
    public static void modifyStarWord(char ch, String word,
            StringBuilder starWord) {
        // TODO - complete this function

    }

    public static void main(String[] args) {
        // TODO - complete this function

    }

}

You can use the following word list for your program, but the list below is the one that the test cases will use. Create a new text file in your project directory and paste the following words into it. Note that your program must be able to deal correctly with blank lines (i.e. ignore them when it reads the file and do not add empty strings to the word list).

MIGHTY
crimes
FLIGHT
FRIGHT
Grimes

PLACES
TRACES

plates
Fisher
fishes

WISHES
dishes

When your program runs, you must be able to produce the following transcript. Note the behavior that the transcript produces when the player tries to guess a character they have previously guessed, when they enter blank lines for the character or the word guess, and when they enter anything but a 'Y' or 'N' (upper or lowercase) for the rematch question.

Enter a random seed: 33
Enter a filename for your wordlist: words.txt
Read 12 words from the file.

The word to guess is: ******
Previous characters guessed: []
Enter a character to guess: f
The character F occurs in 1 positions.

The word to guess is: F*****
Enter your guess for the word: flames
That is not the word.

The word to guess is: F*****
Previous characters guessed: [F]
Enter a character to guess: i
The character I occurs in 1 positions.

The word to guess is: F*I***
Enter your guess for the word: flight
That is not the word.

The word to guess is: F*I***
Previous characters guessed: [F, I]
Enter a character to guess: tjkl
Enter only a single character!
Enter a character to guess: 
Enter only a single character!
Enter a character to guess: t
The character T occurs in 1 positions.

The word to guess is: F*I**T
Enter your guess for the word: 
That is not the word.

The word to guess is: F*I**T
Previous characters guessed: [F, I, T]
Enter a character to guess: o
The character O occurs in 0 positions.

The word to guess is: F*I**T
Enter your guess for the word: flitter
That is not the word.

The word to guess is: F*I**T
Previous characters guessed: [F, I, T, O]
Enter a character to guess: G
The character G occurs in 1 positions.

The word to guess is: F*IG*T
Enter your guess for the word: fight
That is not the word.

The word to guess is: F*IG*T
Previous characters guessed: [F, I, T, O, G]
Enter a character to guess: h
The character H occurs in 1 positions.

The word to guess is: F*IGHT
Enter your guess for the word: Fright
Yes! FRIGHT is the correct word!
That took you 6 guesses.
Would you like a rematch [Y/N]?: jsdf
Please enter only a Y or an N.
Would you like a rematch [Y/N]?: 
Please enter only a Y or an N.
Would you like a rematch [Y/N]?: yes
Please enter only a Y or an N.
Would you like a rematch [Y/N]?: no
Please enter only a Y or an N.
Would you like a rematch [Y/N]?: n
Goodbye!

Another run of the same program should be able to produce the following transcript:

Enter a random seed: 2048
Enter a filename for your wordlist: words.txt
Read 12 words from the file.

The word to guess is: ******
Previous characters guessed: []
Enter a character to guess: s
The character S occurs in 1 positions.

The word to guess is: *****S
Enter your guess for the word: slimes
That is not the word.

The word to guess is: *****S
Previous characters guessed: [S]
Enter a character to guess: r
The character R occurs in 1 positions.

The word to guess is: *R***S
Enter your guess for the word: grimes
That is not the word.

The word to guess is: *R***S
Previous characters guessed: [S, R]
Enter a character to guess: c
The character C occurs in 1 positions.

The word to guess is: CR***S
Enter your guess for the word: crimes
Yes! CRIMES is the correct word!
That took you 3 guesses.
Would you like a rematch [Y/N]?: y

The word to guess is: ******
Previous characters guessed: []
Enter a character to guess: s
The character S occurs in 2 positions.

The word to guess is: **S**S
Enter your guess for the word: dishes
That is not the word.

The word to guess is: **S**S
Previous characters guessed: [S]
Enter a character to guess: f
The character F occurs in 1 positions.

The word to guess is: F*S**S
Enter your guess for the word: fishes
Yes! FISHES is the correct word!
That took you 2 guesses.
Would you like a rematch [Y/N]?: y

The word to guess is: ******
Previous characters guessed: []
Enter a character to guess: s
The character S occurs in 1 positions.

The word to guess is: *****S
Enter your guess for the word: slimes
That is not the word.

The word to guess is: *****S
Previous characters guessed: [S]
Enter a character to guess: r
The character R occurs in 1 positions.

The word to guess is: *R***S
Enter your guess for the word: drimes
That is not the word.

The word to guess is: *R***S
Previous characters guessed: [S, R]
Enter a character to guess: g
The character G occurs in 1 positions.

The word to guess is: GR***S
Enter your guess for the word: grimes
Yes! GRIMES is the correct word!
That took you 3 guesses.
Would you like a rematch [Y/N]?: n
Goodbye!
0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

public class WordGuessing {
  
private static Scanner keyboard;
public static void main(String[] args)
{
List words;
List previousGuesses;
char yesNo = 0;
String wordGuess;
StringBuilder sb;
int guesses = 0;
  
words = new ArrayList();
previousGuesses = new ArrayList();

System.out.print("Enter a random seed: ");
keyboard = new Scanner(System.in);
long seed = keyboard.nextLong() * System.currentTimeMillis();
Random rand = new Random(seed);
keyboard.nextLine();
System.out.print("Enter a file name: ");
String fname = keyboard.nextLine();
words = readWords(fname);
System.out.println("Read " + words.size() + " from the file.\n");
do
{
String word = getRandomWord(rand, words);
String theStarWord;
sb = starWord(word);
do
{
theStarWord = sb.toString();
System.out.println("The word to guess is: " + theStarWord);
if(guesses > 0)
{
System.out.print("Enter your guess for the word: ");
wordGuess = keyboard.nextLine().toUpperCase();
if(wordGuess.equals(word))
{
System.out.println("Yes! " + word + " is the correct word!\nThat took you " + guesses + " guesses.");
break;
}
else
{
System.out.println("That is not the word!\n");
}
}
System.out.println("Previous characters guessed: " + previousGuesses);
char userGuess = getCharacterGuess(keyboard);
previousGuesses.add(userGuess);
int characterCount = charCount(userGuess, word);
System.out.println("The character " + userGuess + " occurs in " + characterCount + " positions.\n");
modifyStarWord(userGuess, word, sb);
guesses++;
}while(!theStarWord.equals(word));
  
System.out.print("Would you like a rematch[Y/N]?: ");
yesNo = keyboard.nextLine().charAt(0);
if(yesNo == 'n' || yesNo == 'N')
{
System.out.println("\nGoodbye!\n");
break;
}
guesses = 0;
words.removeAll(words);
previousGuesses.removeAll(previousGuesses);
  
}while (yesNo != 'n' || yesNo != 'N');
}
/**
* Takes a filename as input. Reads a list of words from the file into a
* list and returns the list. Ensures that all of the words in the list are
* in UPPERCASE (i.e. transforms lowercase letters to uppercase before
* adding them to the list). Assumes that the file will be correctly
* formatted with one word per line. If the file cannot be read prints the
* error message "ERROR: File fname not found!" where "fname" is the name of
* the file and returns an empty list. Note that the order of the words in the
* list must be the same as the order of the words in the file to pass the
* test cases.
*
* @param fname
* the name of the file to read words from
* @return a list of words read from the file in all uppercase letters.
*/
public static List readWords(String fname)
{
List words = new ArrayList();
File file = new File(fname);
try {
Scanner fileScanner = new Scanner(file);
while(fileScanner.hasNext())
{
words.add(fileScanner.next().toUpperCase().trim());
}
} catch (FileNotFoundException ex) {
System.out.println("File " + fname + " not found!");
System.exit(0);
}
return words;
}
  
/**
* Takes a Random object and a list of strings and returns a random String
* from the list. Note that this method must not change the list. The list
* is guaranteed to have one or more elements in it.
*
* @param rnd
* Random number generator object
* @param inList
* list of strings to choose from
* @return an element from a random position in the list
*/
public static String getRandomWord(Random rnd, List inList)
{
int randNum = rnd.nextInt(inList.size());
return (inList.get(randNum).toString());
}
  
/**
* Given a String, returns a StringBuilder object that is the same length
* but is only '*' characters. For example, given the String DOG as input
* returns a StringBuilder object containing "***".
*
* @param inWord
* The String to be starred
* @return a StringBuilder with the same length as inWord, but all stars
*/
public static StringBuilder starWord(String inWord)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < inWord.length(); i++)
{
sb.append('*');
}
return sb;
}
  
/**
* Prompts the user to enter a single character. If the user enters a blank
* line or more than one character, give an error message as given in the
* assignment and prompt them again. When the user enters a single
* character, return the uppercase value of the character they typed.
*
* @param inScanner
* A scanner to take user input from
* @return the uppercase value of the character typed by the user.
*/
public static char getCharacterGuess(Scanner inScanner)
{
String guess;
do
{
System.out.print("Enter a character to guess: ");
guess = inScanner.nextLine();
if(guess.length() != 1)
{
System.out.println(guess + " is not a valid character!");
}
}while(guess.length() != 1);
return (Character.toUpperCase(guess.charAt(0)));
}
  
/**
* Count the number of times the character ch appears in the String word.
*
* @param ch
* character to count.
* @param word
* String to examine for the character ch.
* @return a count of the number of times the character ch appears in the
* String word
*/
public static int charCount(char ch, String word)
{
int counter = 0;
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == ch)
counter++;
}
return counter;
}
  
/**
* Modify the StringBuilder object starWord everywhere the char ch appears
* in the String word. For example, if ch is 'G', word is "GEOLOGY", and
* starWord is "**O*O*Y", then this method modifies starWord to be
* "G*O*OGY". Your code should assume that word and starWord are
* the same length.
*
* @param ch
* the character to look for in word.
* @param word
* the String containing the full word.
* @param starWord
* the StringBuilder containing the full word masked by stars.
*/
public static void modifyStarWord(char ch, String word, StringBuilder starWord)
{
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == ch)
starWord.setCharAt(i, ch);
}
}
}

Add a comment
Know the answer?
Add Answer to:
For this lab you will write a Java program that plays a simple Guess The Word...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please help with this Intro to programming in C assignment! Intro to Programming in C-Large Program...

    Please help with this Intro to programming in C assignment! Intro to Programming in C-Large Program 3 - Hangman Game Assignment purpose: User defined functions, character arrays, c style string member functions Write an interactive program that will allow a user to play the game of Hangman. You will need to: e You will use four character arrays: o one for the word to be guessed (solution) o one for the word in progress (starword) o one for all of...

  • You will be writing a simple Java program that implements an ancient form of encryption known...

    You will be writing a simple Java program that implements an ancient form of encryption known as a substitution cipher or a Caesar cipher (after Julius Caesar, who reportedly used it to send messages to his armies) or a shift cipher. In a Caesar cipher, the letters in a message are replaced by the letters of a "shifted" alphabet. So for example if we had a shift of 3 we might have the following replacements: Original alphabet: A B C...

  • Write a program to play "guess my number". The program should generate a random number between...

    Write a program to play "guess my number". The program should generate a random number between 0 and 100 and then prompt the user to guess the number. If the user guesses incorrectly the program gives the user a hint using the words 'higher' or 'lower' (as shown in the sample output). It prints a message 'Yes - it is' if the guessed number is same as the random number generated. ANSWER IN C LANGUAGE. ====================== Sample Input / Output:...

  • Note wordBank, an array of 10 strings (char *s). Your program should do the following: 1....

    Note wordBank, an array of 10 strings (char *s). Your program should do the following: 1. Select a word at random from the wordBank. This is done for you. 2. On each turn display the word, with letters not yet guessed showing as *'s, and letters that have been guessed showing in their correct location 3. The user should have 10 attempts (?lives?). Each unsuccessful guess costs one attempt. Successful guesses do NOT count as a turn. 4. You must...

  • Original question IN JAVA Show the user a number of blank spaces equal to the number...

    Original question IN JAVA Show the user a number of blank spaces equal to the number of letters in the word For cat, you would show _ _ _. Prompt a user to guess a letter until they have run out of guesses or guessed the full word By default, the user should be able to make 7 failed guesses before they lose the game. If the user guesses a letter that is in the target word, it does not...

  • For this lab you will write a Java program using a loop that will play a...

    For this lab you will write a Java program using a loop that will play a simple Guess The Number game. Th gener e program will randomly loop where it prompt the user for a ate an integer between 1 and 200 (including both 1 and 200 as possible choices) and will enter a r has guessed the correct number, the program will end with a message indicating how many guesses it took to get the right answer and a...

  • Overview In this exercise you are going to recreate the classic game of hangman. Your program...

    Overview In this exercise you are going to recreate the classic game of hangman. Your program will randomly pick from a pool of words for the user who will guess letters in order to figure out the word. The user will have a limited number of wrong guesses to complete the puzzle or lose the round. Though if the user answers before running out of wrong answers, they win. Requirements Rules The program will use 10 to 15 words as...

  • For this lab you will write a Java program that plays the dice game High-Low. In...

    For this lab you will write a Java program that plays the dice game High-Low. In this game a player places a bet on whether the sum of two dice will come up High (totaling 8 or higher), Low (totaling 6 or less) or Sevens (totaling exactly 7). If the player wins, they receive a payout based on the schedule given in the table below: Choice Payout ------ ------ High 1 x Wager Low 1 x Wager Sevens 4 x...

  • Create a script that presents a word-guessing game. Allow users to guess the word one letter at a...

    Create a script that presents a word-guessing game. Allow users to guess the word one letter at a time by entering a character in a form. Start by assigning a secret word to a variable. After each guess, print the word using asterisks for each remaining letter, but fill in the letters that the user guessed correctly. Store the user’s guess in a form field. For example, if the word you want users to guess is “suspicious” and the user...

  • Hangman is a game for two or more players. One player thinks of a word, phrase...

    Hangman is a game for two or more players. One player thinks of a word, phrase or sentence and the other tries to guess it by suggesting letters or numbers, within a certain number of guesses. You have to implement this game for Single Player, Where Computer (Your Program) will display a word with all characters hidden, which the player needed to be guessed. You have to maintain a dictionary of Words. One word will be selected by your program....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT