//  Scott DeRuiter     7/22/2002
//  Hangman.java
//  Plays the game of hangman, choosing a word randomly from a text file.

public class Hangman   
{

	private String word;
	private String copy;
	private String [] list;
	private int misscount;

	public Hangman ( )   
	{
		word = copy = "";
		list = new String [ 50 ];
		misscount = 0;
	}

	public static void main ( String [] args )   
	{
		Hangman h = new Hangman ( );
		h.GetWordsAndPick ( );
		h.PlayGame ( );
	}

	public void GetWordsAndPick ( )   
	{
		int i = 0;
		TextReader inFile;
		String name = "words.txt";
		inFile = new TextReader ( name );
		while ( !inFile.eof ( ) ) 
		{
			list [ i ] = inFile.readLine ( );
			i++;
		}
		inFile.close ( );
		word = list [ (int) ( Math.random ( )  * i ) ];
		for ( i = 0; i < word.length ( ); i++ )
			copy = copy + "*";
	}

	public void PlayGame ( )   
	{
		boolean done = false, winner = false;
		char letter = ' ';
		do  
		{
			letter = AskForLetter ( );
			winner = LookForLetter ( letter );
			if ( misscount == 6 || winner == true )
				done = true;
		} while ( !done );
		if ( winner )
			System.out.println ( "\n\nGood work! YOU ARE A WINNER!\n\n" );
		else
			System.out.println ( "\n\nSorry, but you lost. The word was . . . " );
		System.out.println ( "\n\n" + word + "\n\n" );
	}

	public char AskForLetter ( )   
	{
		TextReader console = new TextReader ( );
		System.out.println ( "\n\nHere is the current word:  " + copy );
		System.out.println ( "\n\nYou have made " + misscount + " wrong guesses so far." );
		System.out.print ( "\n\nEnter a letter to check:  " );
		char input = console.readlnChar ( );
		return input;
	}

	public boolean LookForLetter ( char letter )   
	{
		boolean match = false;
		for ( int i = 0; i < word.length ( ); i++ )
			if ( word.charAt ( i ) == letter )  
			{
				copy = copy.substring ( 0, i ) + letter + copy.substring ( i + 1 );
				match = true;
			}
		if ( !match )
			misscount++;
		if ( copy.equals ( word ) )
			return true;
		else
			return false;
	}
}

Back to Lesson 15 Examples

Back to Java Main Page