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

Need some help with my java program assignment. I need help with some parts of t

ID: 3697784 • Letter: N

Question

Need some help with my java program assignment. I need help with some parts of the assignment (the bold words).

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

Assignment:

Change the Hangman program to be playable throught the network. A good strategy would be to create a hierarchy where Hangman can take an input stream and and output stream throught its constructor method, and then create two driver classes(Server class & Client Class). The game can then create a network-enabled game and pass it the appropriate streams.

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

package networkhangman;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class Hangman {

  
   /*
   * Constructor method for getting input stream and outputStream
   * and setting up the Hangman game
   */
   public Hangman(Socket stream) throws IOException{
       String[] wordArray = getWordsFromFile("word.txt");
       String word = getRandomWord(wordArray);
       playGame(word, stream);
   }
  
  
   /*
   * Get the user name
   * Precondition: The user has a name
   * Postcondition: User name has been determined
   * @return name
   */
   public String getName(BufferedReader input) throws IOException {
       System.out.print("Enter your name: ");
       BufferedReader bufferRead = new BufferedReader((input));
       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, Socket stream) throws IOException {
       ArrayList list = new ArrayList();
       BufferedReader input = new BufferedReader(new InputStreamReader(stream.getInputStream()));      
       PrintWriter out = new PrintWriter(new OutputStreamWriter(stream.getOutputStream()));
       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(input);
       while (!isWordComplete(guessArray) && numGuess < 5) {
           System.out.print("Current word: ");
           printCharArray(guessArray);
           System.out.println();
           System.out.print("Enter your guess: ");

           char guess = input.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++;
           }

           out.println(numCorrect + " letters found");
           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();

       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 networkhangman;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
* A socket server
*/
public class HangmanServer {

   private ServerSocket serverSocket;
   private int port;

   public HangmanServer(int port) {
       this.port = port;
   }

   public void start() throws IOException {
       System.out.println("Starting the socket server at port:" + port);
       serverSocket = new ServerSocket(port);

       // Listen for clients. Block till one connects
       System.out.println("Waiting for clients...");
       Socket client = serverSocket.accept();
       Hangman game = new Hangman(client);
   }

   /**
   * Creates a SocketServer object and starts the server.
   *
   * @param args
   */
   public static void main(String[] args) {
       // Setting a default port number.
       int portNumber = 9000;

       try {
           // initializing the Socket Server
           HangmanServer socketServer = new HangmanServer(portNumber);
           socketServer.start();

       } catch (IOException e) {
           e.printStackTrace();
       }
   }
}

package networkhangman;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
* A Socket client that connects to our socket server
*/
public class HangmanClient {

   private String hostname;
   private int port;
   Socket socketClient;

   public HangmanClient(String hostname, int port) {
       this.hostname = hostname;
       this.port = port;
   }

   public void connect() throws UnknownHostException, IOException {
       System.out.println("Attempting to connect to " + hostname + ":" + port);
       socketClient = new Socket(hostname, port);
       System.out.println("Connection Established");
      
       BufferedReader in = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
PrintWriter out = new PrintWriter(socketClient.getOutputStream());

out.write("Hello, Server");

String s = in.readLine();
System.out.println("Client Recieved: " + s);
   }

   public static void main(String arg[]) {
       // Creating a SocketClient object
       HangmanClient client = new HangmanClient("localhost", 9000);
       try {
           // trying to establish connection to the server
           client.connect();
          

       } catch (UnknownHostException e) {
           System.err.println("Host unknown. Cannot establish connection");
       } catch (IOException e) {
           System.err.println("Cannot establish connection. Server may not be up." + e.getMessage());
       }
   }
}

Explanation / Answer

/////////////////////////////////////////////////////////////////////////////// // Title: Hangman // Files: Hangman.java //////////////////////////// 80 columns wide ////////////////////////////////// import java.util.*; /** * This program implements the word guessing game called Hangman. * *

Bugs: none known * * @author CS302, 2009,2012 modified by Jim Skrentny */ public class Hangman { ////////////////////////////////////////////////////////////////////// // 1. CLASS VARIABLE ////////////////////////////////////////////////////////////////////// private static String [] words = //choose secret word from these {"geography", "cat", "yesterday", "java", "truck", "opportunity", "fish", "token", "transportation", "bottom", "apple", "cake", "remote", "pocket", "terminology", "arm", "cranberry", "tool", "caterpillar", "spoon", "watermelon", "laptop", "toe", "toad", "fundamental", "capitol", "garbage", "anticipate", "apple"}; ////////////////////////////////////////////////////////////////////// // 2. INSTANCE VARIABLES ////////////////////////////////////////////////////////////////////// private String secretWord; // the chosen secret word private ArrayList correctLetters; // correct guesses private ArrayList incorrectLetters; // incorrect guesses private Scanner stdin = new Scanner(System.in); // for user input ////////////////////////////////////////////////////////////////////// // 3. CONSTRUCTOR ////////////////////////////////////////////////////////////////////// /** * Constructs a Hangman game. */ public Hangman() { //REMOVE LINE BELOW WHEN DONE TESTING this.secretWord = "miscellaneous"; //Randomly choose a word from list of words //UNCOMMENT LINES BELOW TO PLAY WHEN DONE TESTING //Random randIndex = new Random(); //int index = randIndex.nextInt(Hangman.words.length); //this.secretWord = Hangman.words[index]; this.correctLetters = new ArrayList(); for (int i = 0; i = 4) { System.out.println(" | \|/"); } } if (badGuesses > 4) { poleLines = 3; if (badGuesses == 5) { System.out.println(" | /"); } else if (badGuesses >= 6) { System.out.println(" | / \"); } } if (badGuesses == 7) { poleLines = 1; } for (int k = 0; k

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