Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA Since the way the program is currently written requires one player to enter

ID: 3739823 • Letter: J

Question

JAVA

Since the way the program is currently written requires one player to enter a word and another to play, change the program so that one player may play (without cheating!). In order to do this, add an array to the program and allow the user to enter 25 words that will populate the array. Then add a random number generator to select an index that will then be used to randomly pick one of the word from the word list array to use as the original word to guess. Note: In Unit 3, we will be modifying this program one more time to populate the array from a word list file instead of user input.)

Add accumulators to keep track of total number of correct guesses, total number incorrect guesses and total guesses. Display these totals at the end of the game.

//Simulates the Hangman Game: Part 2 - CPP Version modifications

//Original - allows only 5 letter words

//Part 2 modifications:

//      - allows any length of word

//      - keeps track of letters already used

//            - notifies user that letter has already been used before asking for another letter

//            - repeat letter not counted in incorrect guesses

//            - notifies user of how many guesses they have left when they guess incorrectly

import java.io.*;

import java.util.*;

public class Hangman

{

    public static void main(String[] args)

    {

        //declare variables

        String origWord = "";

        String letter = "";

        boolean dashReplaced = false;

        boolean gameOver = false;

        int numIncorrect = 0;

        int guessesLeft = 10;

        String guessWord = "";

        int numChars = 0;

        String updatedWord = "";

        String usedLetters = "";

        int usedSub = 0;

        Scanner dataIn = new Scanner(System.in);

        //get the original word from player 1

        System.out.println("Enter the original word: ");

        origWord = dataIn.nextLine();

        numChars = origWord.length(); //determine number of characters in original word

        //convert the original word to uppercase

        origWord = origWord.toUpperCase();

        //assign hyphens/dashes to guessWord equal to number of

        //characters in original word

        for (int i = 0; i < numChars; i++)

        {

            guessWord += "-";

        }//end for

        //clear the window

        for (int x = 0; x < 50; x++)

        {

            System.out.println();

        }//end for

        //begin game

        System.out.println("WORD GUESS GAME");

        //allow player to guess letter; the game is over when either

        //the word is guessed or player makes 10 incorrect guesses

        while (gameOver == false)

        {

            dashReplaced = false;

            //display the used letters

            System.out.print("Used letters: ");

            //append current letter to the usedLetter string

            //followed by a blank space

            for (usedSub = 0; usedSub < usedLetters.length(); usedSub++)

            {

                System.out.print(usedLetters.substring(usedSub, (usedSub + 1)) + " ");

            }//end for

            System.out.println(' ');

            //display guessWord with dashes

            System.out.println("Guess this word: " + guessWord);

            //get a letter from player 2, then convert

            //the letter to uppercase

            System.out.print("Enter a letter ");

            letter = dataIn.nextLine();

            letter = letter.toUpperCase();

            System.out.println(' ');

            usedSub = 0;

            //determine whether the letter has already been entered

            while (usedSub < usedLetters.length() &&

!(usedLetters.substring(usedSub, (usedSub + 1)).equals(letter)))

            {

                usedSub++;

            }//end while

            if (usedSub < usedLetters.length())

            {

                System.out.println("You already guessed letter " + letter);

            }

            else

            {

                //append current letter to usedLetter string

                usedLetters += letter;

                //search for the letter in the original word

                //if player correctly guessed a letter, replace dash

                //appropriate dash with guessed letter

                for (int x = 0; x < numChars; x++)

                {

                    if (origWord.indexOf(letter, x) >= 0)

                    {

                        updatedWord = guessWord.substring(0, origWord.indexOf(letter, x));

                        updatedWord += letter;

                        updatedWord += guessWord.substring(origWord.indexOf(letter, x) + 1,

                       guessWord.length());

                        //updated word has replaced the appropriate

                        //dash with guessed letter - assign to guessWord

                        guessWord = updatedWord;

                        //indicate that a replacement was made

                        dashReplaced = true;

                    }//end if

                }//end for

                //determine whether a replacement was made

                if (dashReplaced == true)

                {

                    //if the word does not contain any dashes,

                    //then the user guessed the word, so the game is over

                    if (guessWord.indexOf('-') == -1)

                    {

                        gameOver = true;

                        System.out.println("Yes, the word is " + guessWord);

                        System.out.println("Great guessing! You win!");

                    }//end if

                }

                else //processed when no dash was replaced

                {

                    //increment the counter for incorrect guesses

                    numIncorrect++;

                    guessesLeft--;

                    //display guesses left

                    System.out.println("You have " + guessesLeft + " guesses left");

                    // determine whether player made 10 incorrect guesses

                    if (numIncorrect == 10)

                    {

                        //the game is over

                        gameOver = true;

                        System.out.println("Sorry. you lose. You made too many incorrect guesses.");

                        System.out.println("The word is " + origWord);

                    }//end if

                }//end if

            }//end if

        }//end while

    }//end main

}//end class

Explanation / Answer

Hangman.java

import java.util.Random;

import java.util.Scanner;

public class Hangman {

/*

* Creating an Scanner class object which is used to get the inputs entered

* by the user

*/

static Scanner sc = new Scanner(System.in);

static int totalMiss=0,totalMatch=0;

public static void main(String[] args) {

//Declaring variables

char ch;

int rand;

//Creating an String array

String[] words = { "Star Wars: The Last Jedi","Get Out","DunKirk","Logan","Blade Runner","The Matrix","Avatar","Coco","Baby Driver","FistFight","Lady Bird","Cars","Logan Lucky","Aliens","Jigsaw","Titanic","The Graduate","Inception","The Shining","West Side Story","Annie Hall","The Avengers","Double Indemnity","Chinatown","Taxi Driver"};

// Creating an random class object

Random r = new Random();

/*

* This while loop continues to execute until the user enters a 'y' or

* 'Y'

*/

while (true) {

rand = r.nextInt((words.length-1) + 1);

// calling a Method

guessWord(words[rand].toLowerCase());

// Prompting the user to run again

System.out.print(" Do you Want to play again (Y/N):");

ch = sc.next(".").charAt(0);

if (ch == 'y' || ch == 'Y') {

continue;

} else {

System.out.println("Total no of guesses :"+(totalMiss+totalMatch));

System.out.println("Total no of Correct Guesses :"+(totalMatch));

System.out.println("Total no of Wrong guesses :"+(totalMiss));

break;

}

}

}

//This method will ask the user to enter characters until user won or lost the game

private static void guessWord(String string) {

final int NO_OF_MISSES = 7;

char ch;

int flag,noOfGamesWon=0,noOfGamesLost=0,miss=0,match=0;

int len=0;

char arr[] = new char[string.length()];

for (int i = 0; i < string.length(); i++) {

if((string.charAt(i)>=97 && string.charAt(i)<=122) || (string.charAt(i)>=65 && string.charAt(i)<=90))

{

arr[i] ='_';   

len++;

}

else

{

arr[i] = string.charAt(i);

}

}

while (len != 0) {

flag = 0;

match = 0;

System.out.print("Word:");

for (int i = 0; i < string.length(); i++) {

System.out.print(arr[i] + " ");

}

System.out.print(" Pick a letter:");

ch = sc.next(".").charAt(0);

if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {

if (Character.isUpperCase(ch)) {

ch = Character.toLowerCase(ch);

}

} else {

System.out.println("** Not a letter **");

continue;

}

for (int i = 0; i < string.length(); i++) {

if (string.charAt(i) == ch) {

arr[i] = ch;

len--;

flag = 1;

match++;

totalMatch++;

}

}

if (flag == 0) {

System.out.println("There is no letter " + ch + ".");

miss++;

totalMiss++;

if (miss == NO_OF_MISSES) {

System.out.println("You Lost the game.");

System.out.println("The Word is :" + string);

break;

}

} else {

System.out.println("There is " + match + " letter " + ch + ".");

}

}

if (len == 0)

System.out.println("You won the game.");

  

}

}

___________________

Output:

Word:_ _ _ _ _
Pick a letter:a
There is 1 letter a.
Word:_ _ _ a _
Pick a letter:e
There is no letter e.
Word:_ _ _ a _
Pick a letter:i
There is no letter i.
Word:_ _ _ a _
Pick a letter:o
There is 1 letter o.
Word:_ o _ a _
Pick a letter:u
There is no letter u.
Word:_ o _ a _
Pick a letter:s
There is no letter s.
Word:_ o _ a _
Pick a letter:l
There is 1 letter l.
Word:l o _ a _
Pick a letter:g
There is 1 letter g.
Word:l o g a _
Pick a letter:n
There is 1 letter n.
You won the game.

Do you Want to play again (Y/N):Y
Word:_ _ _ _ _ _ _ _ _ _ _
Pick a letter:t
There is 1 letter t.
Word:t _ _ _ _ _ _ _ _ _ _
Pick a letter:h
There is 1 letter h.
Word:t h _ _ _ _ _ _ _ _ _
Pick a letter:e
There is 3 letter e.
Word:t h e _ _ e _ _ e _ _
Pick a letter:a
There is 1 letter a.
Word:t h e a _ e _ _ e _ _
Pick a letter:v
There is 1 letter v.
Word:t h e a v e _ _ e _ _
Pick a letter:n
There is 1 letter n.
Word:t h e a v e n _ e _ _
Pick a letter:g
There is 1 letter g.
Word:t h e a v e n g e _ _
Pick a letter:r
There is 1 letter r.
Word:t h e a v e n g e r _
Pick a letter:s
There is 1 letter s.
You won the game.

Do you Want to play again (Y/N):N
Total no of guesses :20
Total no of Correct Guesses :16
Total no of Wrong guesses :4

____________Thank you