Hey I am almost done with my hangman game for java but Im having a tough time in getting the last bit of it. I have included ALOT of comments for you guys to help me out with it.
import java.io.*;
import java.util.*;
import javax.swing.*;
public class Hangman
{
public static void main(String[] args) throws Exception
{
boolean[] wordsUsed = new boolean[50];
int totalGuesses = 0;
int wrongGuesses = 0;
File wordFile = new File("F:\\randomwords.txt");
Scanner input = new Scanner(wordFile);
String[] list = new String[50];
for(int i = 0; i <= list.length - 1; i++)
{
list[i] = input.nextLine();
}
// Picking a word at random
int randomWordNo;
do
{
randomWordNo = (int)(Math.random() * 50);
}
while (wordsUsed[randomWordNo]);
wordsUsed[randomWordNo] = true;
String theWordToGuess = list[randomWordNo];
// Create StringBuilder to hold the word as-guessed so far
// That starts out as the word TO guess, and then we change
// the letters into asterisks. As the player guesses letters,
// they'll change back from asterisks to letters, until
// wordSoFar again becomes the same as theWordToGuess, at
// which point the player has solved the puzzle.
//
StringBuilder wordSoFar = new StringBuilder(theWordToGuess);
for(int k = 0; k < wordSoFar.length(); k++)
{
wordSoFar.setCharAt(k, '*');
}
// Now we go into a loop, asking the user for letters.
// If the letter is NOT in the string, it's a wrong guess,
// and we go again.
//
// If the letter IS in the string, then we change the characters
// in wordSoFar from asterisks to the actual letter, and credit
// the user with a correct guess.
//
// we continue until wordSoFar matches theWordToGuess
do
{
// Prompt the user for the next character to guess
System.out.println("Guess a letter" );
// Look at wordSoFar to see if the character they guessed is
// already there. If so, they've (rather stupidly) guessed
// a character they've already successfully guessed.
// If not, then look at theWordToGuess, and see if the letter
// they just guessed is THERE. If not, then count this as a
// wrong guess and go again
// If SO, then for all positions in wordSoFar, change the
// (current) asterisk to the character they just guessed,
// if that character is in the same location in theWordToGuess
} while (wordSoFar.indexOf(theWordToGuess) == 0);
System.out.println("Congratulations you solved the problem in " + totalGuesses + " guesses, with " + wrongGuesses + " incorrect guesses");
}
}