Need help with java program assignment. ----------------------------------------
ID: 3693888 • Letter: N
Question
Need help with java program assignment.
------------------------------------------------------------------------------
Assignment:
Change your 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.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 playAround(String word) throws IOException {
ArrayList<Character> list = new ArrayList<Character>();
Scanner sc = new Scanner(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 = sc.next().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 FileNotFoundException
*/
public int getNumberOfWordsInFile(String fileName) throws FileNotFoundException {
int wordCount = 0;
File file = new File("word.txt");
Scanner sc = new Scanner(new FileInputStream(file));
sc.nextLine();
int count = 0;
while (sc.hasNext()) {
String line = sc.nextLine();
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 FileNotFoundException
*/
public String[] getWordsFromFile(String fileName) throws FileNotFoundException {
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.playAround(word);
}
}
Explanation / Answer
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