Answer:
See explaination
Step-by-step explanation:
Program source code
import java.util.Random;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class hangman {
public static void main(String args[]) {
//ArrayList to store the dictionary
ArrayList<String> dict = new ArrayList<String>();
//to read the dictionary into ArrayList
BufferedReader fileReader;
try {
//change path to your dict file
fileReader = new BufferedReader(new FileReader(
"/Users/username/Downloads/dict.txt"));
String line = fileReader.readLine();
//read line by line into ArrayList
while (line != null) {
dict.add(line);
line = fileReader.readLine();
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
//OR COMMENT THE ABOVE READING FROM FILE, to test with this 6 words
// dict.add("volvo");
// dict.add("apple");
// dict.add("ball");
// dict.add("cat");
// dict.add("elephant");
// dict.add("zoo");
int RAND_MIN=3,RANDMAX=9;
int maxGuesses = 10;
String chosenWord = "", resWord="";
Boolean isChosen = false;
Random r = new Random();
int randLength = r.nextInt((RANDMAX - RAND_MIN) + 1) + RAND_MIN;
System.out.println("Random length = " + randLength );
for (int i = 0; i < dict.size(); i++) {
if(dict.get(i).length() != randLength)
{
dict.remove(i);
i--;
}
}
//uncomment the println lines below to see the working of the algorithm
Scanner in = new Scanner(System.in);
int guessCounter = maxGuesses;
while(guessCounter>0)
{
System.out.println( "\\\\\\words left are: and chosen is: " + isChosen);
for (int i = 0; i < dict.size(); i++) {
System.out.println(dict.get(i) );
}
guessCounter--;
System.out.println( "\\Enter a letter:" );
String letter = in.nextLine();
if(isChosen==false){
//delaying choosing random word by removing words based on given letter
int matchCount=0;
for (int i = 0; i < dict.size(); i++) {
if(dict.get(i).indexOf(letter.charAt(0)) != -1)
{
matchCount++;
}
}
if(matchCount!=dict.size())
{
for (int i = 0; i < dict.size(); i++) {
if(dict.get(i).indexOf(letter.charAt(0)) != -1)
{
dict.remove(i);
i--;
}
}
}
//choosing the mystery word if there'll be no words left in ArrayList
else{
chosenWord = dict.get(0);
resWord = chosenWord;
isChosen = true;
chosenWord = chosenWord.replace(letter.charAt(0)+"","");
//System.out.println("remaining word: "+ chosenWord);
if(chosenWord=="")
{
System.out.println( "you've cracked the word: " + chosenWord + " in Guesses:" + (maxGuesses-guessCounter));
return;
}
}
}
//if guessed all letters of chosen word
else{
chosenWord = chosenWord.replace(letter.charAt(0)+"","");
//System.out.println("remaining worrd: "+ chosenWord + " : " + chosenWord.length());
if(chosenWord.length()==0)
{
System.out.println( "you've cracked the word: " + resWord + " in Guesses:" + (maxGuesses-guessCounter));
return;
}
}
}
//if ran out of guesses
System.out.println( "you've ran out of your guesses, the word is: " + resWord);
return;
}
}