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

Need some help with java program assignment. -----------------------------------

ID: 3694848 • Letter: N

Question

Need some help with java program assignment.

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

Assignment:

Change the Hangman program to be playable via the network. A good strategy would be to create a hierarchy where Hangman can take an input stream and and output stream via its constructor method, and then create two driver classes. Your game can then create a network-enabled game and pass it the appropriate streams. The program would look something like this:

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

package hangman;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class Hangman {

  
   /*
   * Get the user name
   * Precondition: The user has a name
   * Postcondition: User name has been determined
   * @return name
   */
   public String getName() throws IOException {
       System.out.print("Enter your name: ");
       BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
       String name = bufferRead.readLine();

       return name;
   }

   /*
   * Executing the Hangman game
   * Precondition: There is words in the text file.
   * Postcondition: The Hangman game has been played.
   * @throws IOException
   */
   public void playGame(String word) throws IOException {
       ArrayList list = new ArrayList();
       BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
       FileWriter writer = new FileWriter("wordsnew.txt");
       char[] guessArray = setDefaultCharArray(word.length());
       char[] wordArray = word.toCharArray();
       int numGuess = 0;
       int numCorrect = 0;
       int numberOfTurn = 0;
       String name = getName();
       while (!isWordComplete(guessArray) && numGuess < 5) {
           System.out.print("Current word: ");
           printCharArray(guessArray);
           System.out.println();
           System.out.print("Enter your guess: ");

           char guess = bufferRead.readLine().charAt(0);
           numberOfTurn++;
           for (int i = 0; i < list.size(); i++) {
               if (list.get(i) == guess) {
                   numberOfTurn--;
                   numGuess--;
               }
           }
           boolean found = false;
           for (int i = 0; i < guessArray.length; i++) {
               if (guessArray[i] == '_' && wordArray[i] == guess) {
                   numCorrect++;
                   guessArray[i] = wordArray[i];
                   found = true;

               }
           }
           if (!found) {
               list.add(guess);
               numGuess++;
           }

           System.out.println(numCorrect + " letters found");
           System.out.println();
           if (numGuess == 5) {
               System.out.println();
               System.out.println("Sorry, you lost.");
           } else if (isWordComplete(guessArray))
               System.out.println("You had won");

           if (numGuess == 5)

           {
               writer.write("Sorry, you lost.");
           } else if (

           isWordComplete(guessArray))
               writer.write("You had won");
       }
       writer.close();

       System.out.println("Name: " + name);
       System.out.println("The word is " + word);
       System.out.println(numberOfTurn + " turns");
   }

   /**
   * This method counts the number of words in a given file and returns that
   * number.
   * Precondition: There is a file that exist
   * Postcondition: The number of words has been determined.
   * @param fileName
   * @return wordCount
   * @throws IOException
   */
   public int getNumberOfWordsInFile(String fileName) throws IOException {
       int wordCount = 0;
       File file = new File("word.txt");
       Scanner sc = new Scanner(new FileInputStream(file));
       FileReader fileReader = new FileReader("word.txt");
       BufferedReader bufferedReader = new BufferedReader(fileReader);
       String skip = bufferedReader.readLine();
       String line = null;
       while ((line = bufferedReader.readLine()) != null) {
           if (line.startsWith(";") || line.startsWith("#")) {
               sc.nextLine();
               wordCount--;
           } else
               sc.next();
           wordCount++;

       }
       return wordCount;
   }

   /**
   * This method accepts a file name. First it gets the number of words in the
   * file by calling the getNumberOfWordsInFile method. Then it creates a
   * String array based on how many words are in the file. Next, it fills the
   * array with all of the words from the file. Then it returns the array.
   *
   * Precondition: There is words in the text file
   * Postcondition: The certain word had been determined
   *
   * @methodName getWordsFromFile
   * @param fileName
   * @return wordArray
   * @throws IOException
   */
   public String[] getWordsFromFile(String fileName) throws IOException {
       int wordCount = getNumberOfWordsInFile("word.txt");
       String[] wordArray = new String[wordCount];
       File file = new File("word.txt");
       Scanner sc = new Scanner(new FileInputStream(file));
       sc.nextLine();
       int i = 0;
       while (sc.hasNext()) {
           String line = sc.nextLine();
           if (line.startsWith(";") || line.startsWith("#")) {
               sc.nextLine();
               i--;
           } else
               wordArray[i] = sc.next();
           i++;
       }
       sc.close();
       return wordArray;
   }

   /**
   * This method returns a random string from a given String array
   * Precondition: The element is a string
   * Postcondition: Random string has been return
   *
   * @methodName getRandomWord
   * @param wordArray
   * @return randomWord
   */
   public String getRandomWord(String[] wordArray) {
       String randomWord = null;
       Random rd = new Random();
       try {
           int count = getNumberOfWordsInFile("word.txt");
           int randNo = rd.nextInt(count - 1);
           randomWord = wordArray[randNo];
           while (count - 1 < randNo) {
               if (count - 1 < randNo) {
                   randomWord = wordArray[randNo];
                   break;
               } else
                   randNo = rd.nextInt(count - 1);
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
       return randomWord;
   }

   /**
   * This method accepts an int and creates a char array of that size. Then it
   * sets each element in the array to an underscore '_' Then it returns the
   * char array.
   * Precondition: There is words in the text file
   * Postcondition: The size of the word has been determined
   *
   * @methodName setDefaultCharArray
   * @param size
   * @return charArray
   */
   public char[] setDefaultCharArray(int size) {
       char[] charArray = new char[size];
       for (int i = 0; i < charArray.length; i++)
           charArray[i] = '_';
       return charArray;
   }

   /**
   * This method takes the given char array and uses a loop to print out each
   * element all on the same line.
   * Precondition: The array has been determined
   * Postcondition: The given char arrya has been printed
   *
   * @methodName printCharArray
   * @param charArray
   */
   public void printCharArray(char[] charArray) {
       for (int i = 0; i < charArray.length; i++)
           System.out.print(charArray[i]);
   }

   /**
   * This method takes the given char array and checks if any of the elements
   * are equal to an underscore '_' It returns true if the char array contains
   * an underscore '_' and false if it does not.
   * Precondition: The hangman game is ready to be played
   * Postcondition: The word that is being used in hangman has been complete or incomplete
   *
   * @methodName isWordComplete
   * @param charArray
   * @return isComplete
   */
   public boolean isWordComplete(char[] charArray) {
       boolean isComplete = true;
       for (int i = 0; i < charArray.length; i++) {
           if (charArray[i] == '_') {
               isComplete = false;
               break;
           }
       }
       return isComplete;
   }
}

package hangman;

public class HangmanDriver {

/*

   * Executing the Hangman game

   */

   public static void main(String[] args) throws Exception {

       Hangman game = new Hangman();

       String[] wordArray = game.getWordsFromFile("word.txt");

       String word = game.getRandomWord(wordArray);

       game.playGame(word);

   }

}

Explanation / Answer

Answer :

import java.util.Scanner;
   import java.io.*;

    public class Hangmangame
   {
       public static void main(String[] args) throws IOException
      {
         Scanner sc = new Scanner(System.in);
         char repeat = 'n';
         String unknown;
         StringBuffer interupts;
         final int MAXCOUNT = 6;
         int parts_of_body;
         boolean visit;
         String guess;
         String count_guess;
         char alpha_char;
        
         Scanner inputfile = new Scanner(new FileReader("words.txt"));
    
         do {
       
            unknown = inputfile.next();
            count_guess = "";
            visit = false;
            parts_of_body = MAXCOUNT;
       
       
            interupts = makeinterupts(unknown);
         
            while (! visit)
            {
               System.out.println("Here is your word: " + interupts);
               System.out.println("count_guess so far: " + count_guess);
               System.out.print("enter a guess (alpha_char or word): ");
               guess = sc.next();
          
          
               if (guess.length() > 1)
               {
                  if (guess.equals(unknown))
                     System.out.println("you win the game!");
                  else
                     System.out.println("you lost the game");
                  visit=true;
               }
               else
               {
                  alpha_char = guess.charAt(0);
                  count_guess += alpha_char;
                  if (unknown.indexOf(alpha_char) < 0)
                  {   --parts_of_body;
                     System.out.print("bad guess - ");
                  }
                  else
                  {
              
                     matchalpha_char(unknown, interupts, alpha_char);                                 
                  }
                  System.out.println(parts_of_body + "bodyparts are left");
                  if (parts_of_body == 0)
                  {   System.out.println("you lose");
                     visit = true;
                  }
                  if (unknown.equals(interupts.toString()))
                  {   System.out.println("you win!");
                     visit = true;
                  }
               }
          
            }
       
            if (inputfile.hasNext())
            {
               System.out.print("play repeat (y/n)?: ");
               repeat = sc.next().charAt(0);
            }
            else
               System.out.println("thanks for playing (no more words)");
         } while (inputfile.hasNext() && (repeat == 'Y' || repeat == 'y'));
      }



       public static void matchalpha_char(String unknown, StringBuffer interupts, char alpha_char)
      {
         for (int index = 0; index < unknown.length(); index++)
            if (unknown.charAt(index) == alpha_char)
               interupts.setCharAt(index, alpha_char);
         System.out.print("nice guess - ");
      }

       public static StringBuffer makeinterupts(String s)
      {
         StringBuffer interupts = new StringBuffer(s.length());
         for (int count=0; count < s.length(); count++)
            interupts.append('-');
         return interupts;
      }
   

   }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote