Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Help with a hangman game

843789Apr 27 2010 — edited Apr 29 2010
i need to have a character array to hold the word to be guessed, a character array to initially hold an underscore for each letter of the word to be guessed, a character array of unguessed letters, an integer variable to store the number of unguessed letters, a String array to hold the dictionary, and an integer variable to store the number of wrong guesses

You are required to print out a list of all available (unguessed) letters to the screen before each guess. As letters are guessed, deleted the letter from the array. Be sure to delete properly and keep a counter of the number of letters in the array.

You are to use an array of characters to store the word being guessed, and an array of characters with an underscore for each letter to be filled in. As the player correctly guesses a letter, replace the underscore with the letter guessed. When a player makes a correct guess, all instances of that letter should be filled in.

You will be provided with a dictionary.txt file that will serve as your dictionary. dictionary.txt will have an int as the first value, which is the number of words in the file. Store these in an array of Strings. You should generate a random number to determine which word will be played. Use the following code:

Random rand = new Random();//This line of code should be executed only once.

int index = rand.nextInt(numWords); //this will return an integer between 0 (inclusive) and numWords (exclusive). This line of code should be executed every time you choose a new word.

If a player guesses a letter that is not in the word being guessed, increment the number of wrong guesses. After each guess, display the number of misses. You may display a hangman if you wish, but that is not necessary.

If the player fills in all letters, display a ?Win? message. After 7 wrong guesses, display a message that he/she lost and display the word.

Allow a user to play the game repeatedly until he/she chooses to quit.



when i am in my unguessed method and have the user type in a letter, do i need to set that incoming letter to a variable before i try to use my for loop to update the list?

also in my wrongGuess method, I want to assign the next character that the person enters in to a variable called letter. once i do that i want to check if with the word to see if it is indeed a part of the word. if it isnt then i will increment the number of wrong guesses

my teacher is having us read from a file called dictionary.txt and having us use the Random import. we were never taught this so im not exactly sure where i should be putting any of it.

also, i was just looking for a little guidance for setting up the run method to call in main

Here is the code that i have. I am having a lot of difficulties and looking for a little help. Thanks a lot!!




import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;


public class Hangman
{
private char[] word;
private char[] underscore;
private char[] unguessed;
private String[] dictionary;
private int storeUnguessed=26;
private int numberWrong=0;

char letter;
Random rand;
char[] alphabet = new char[26];
{
alphabet[0]='a';
alphabet[1]='b';
alphabet[2]='c';
alphabet[3]='d';
alphabet[4]='e';
alphabet[5]='f';
alphabet[6]='g';
alphabet[7]='h';
alphabet[8]='i';
alphabet[9]='j';
alphabet[10]='k';
alphabet[11]='l';
alphabet[12]='m';
alphabet[13]='n';
alphabet[14]='o';
alphabet[15]='p';
alphabet[16]='q';
alphabet[17]='r';
alphabet[18]='s';
alphabet[19]='t';
alphabet[20]='u';
alphabet[21]='v';
alphabet[22]='w';
alphabet[23]='x';
alphabet[24]='y';
alphabet[25]='z';
}

public Hangman()
{
}

public void unguessed()
{
Scanner in = new Scanner(System.in);
int numLetters=26;
System.out.print("Unguessed Letters: " + alphabet);
System.out.print("Please enter a letter: ");
? // have the user type in a letter then remove it
for(int index=0; index<numLetters-1; index++)
{
alphabet[index]=alphabet[index+1];
}
numLetters--;
}

public void wrongGuess()
{
Scanner in=new Scanner(System.in);

for(int index=0; index<word.length;index++)
{
System.out.print("Please enter a letter: ");
char letter = in.next();
if(letter==word[index])
{

}
else
{
this.numberWrong++;
}
}
}

public void endGame()
{
for(int index=0; index<underscore.length;index++)
{
if(underscore[index]=='_' && numberWrong>7)
{
System.out.print("YOU LOSE! The word was: "
+ this.word);
}
}
}

public void readDictionary()
{
Scanner in=null;
int numWords=0;
try
{
in = new Scanner(new File("dictionary.txt"));
}
catch (FileNotFoundException ex)
{
System.out.print("File not found");
System.exit(1);
}
while(in.hasNext()&& numWords<dictionary.length)
{
dictionary[numWords]=in.next();
numWords++;
}
in.close();
Random rand = new Random();
}

public void gameWord()
{
int numWords=dictionary.length-1;
int index = rand.nextInt(numWords);

String temp=dictionary[index];
word=new char[temp.length()];

}

public void underscoreWord()
{
underscore=new char[word.length];

for(int index=0; index<underscore.length; index++)
{
if(underscore[index]==' ')
{
underscore[index]='_';
}
if(letter==word[index])
{
underscore[index]=letter;
}
}
}

public void run()
{
/* -read in from dictionary
* -choose a random word
* -print out unguessed letters
* -print out underscores
* -ask the user for a letter
* -read in the letter
* -go through word and underscore
* -check to see if it is the end of a game
* -ask for another letter
* ???????
*/


}

public static void main(String [] args)
{
Hangman game = new Hangman();
game.run();
}
}

Comments

843789
Do you have a specific question?

When you post code, please wrap it in code tags. Highlight it and click the CODE button above the text input box.
843789
Sorry i am new to this.. do i put the code between the or where at?

when i am in my unguessed method and have the user type in a letter, do i need to set that incoming letter to a variable before i try to use my for loop to update the list?

also in my wrongGuess method, I want to assign the next character that the person enters in to a variable called letter. once i do that i want to check if with the word to see if it is indeed a part of the word. if it isnt then i will increment the number of wrong guesses

my teacher is having us read from a file called dictionary.txt and having us use the Random import. we were never taught this so im not exactly sure where i should be putting any of it.

also, i was just looking for a little guidance for setting up the run method to call in main
791266
@Op. Please don't cross-post. I removed your other thread.

Kaj
843789
If I were teaching a Java class, the very first thing I'd teach is OO thinking, in particular, creating classes to represent conceptual roles in a program. However if your class is like every other introductory Java class out there, I'm guessing you haven't covered it yet. Am I right?

Assuming you can, I'd suggest creating classes to represent the dictionary, the game, the clue, and the user's state of guessing. At that point, the relationship of parts and how they interact would be clearer.
YoungWinston
opfire6 wrote:
Sorry i am new to this.. do i put the code between the or where at?
1. Copy the code from your Java editor onto the screen.
2. Select ALL the code as normal,
3. Press the CODE button.

PS: I don't know if you've covered the String class yet, but you need to read the API (and it's big).

Just for starters, you can do neat things like:
private char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
(unless you have a really good reason not to, make ALL your instance fields private)

Winston
843789
Well i looked it over again.. and I managed to switch up a lot of things. I however am still having problems with deleting the chosen letters from the array, filling in the underscores with the correct letter guessed, and with continuing to print out the list of letters left to guess for every guess. If anyone can help me out that would be great.

Thanks so much
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;


public class Hangman 
{
	private char[] word;
	private char[] underscore; 
	private char[] unguessed;
	private String[] dictionary;
	private int storeUnguessed=26;
	private int numberWrong=0;
	private char[] alphabet = new char[26];	
	
	public Hangman()
	{						
	}
	
	public void unguessed()
	{
		Scanner in = new Scanner(System.in);
		int numLetters=26;
		System.out.print("Please enter a letter: ");
		String letter=in.next();
		char guess=letter.charAt(0);
		for(int index=0; index<numLetters-1; index++)
		{
			alphabet[index]=alphabet[index+1];
		}
		numLetters--;		
	} 
	
	public void wrongGuess()
	{
		Scanner in=new Scanner(System.in);
		for(int index=0; index<word.length;index++)
		{
			System.out.print("Please enter a letter: ");
			String letter = in.next();
			char guess=letter.charAt(0);
			for(int i=0; i<word.length; i++)
			{
				if(guess==word[index])
				{
					underscore[index]=guess;
				}
				else
				{
					this.numberWrong++;
				}
			}
		}
	}
	
	public boolean containUnderscore()
	{
		boolean result=false;
		int index=0;
		for(int i=0; i<word.length; i++)
		{
			if(this.underscore[index]=='_')
			{
				result = true;
			}
		}
		return result;
	}
	
	public void readDictionary()
	{		
		Scanner in=null; 
		int numWords=0;
		try 
		{
			in = new Scanner(new File("dictionary.txt"));
		}
		catch (FileNotFoundException ex) 
		{
			System.out.print("File not found"); 
			System.exit(1);
		}
		int capacity = in.nextInt();
		dictionary = new String[capacity];
		while(in.hasNext()&& numWords<dictionary.length)
		{
			dictionary[numWords]=in.next();
			numWords++;
		}
		in.close();	
	}
			
	
	public void setup(Random rand)
	{
		int numWords=55;
		int index = rand.nextInt(numWords);
		String wordString=dictionary[index];
		word=new char[wordString.length()];
		for(int i=0; index<word.length-1; index++)
		{
			word[index]=wordString.charAt(index);
		}
		
		underscore=new char[wordString.length()];
		for(int i=0; index<word.length-1; index++)
		{
			underscore[index]='_';
		}
		
		alphabet[0]='a';
		alphabet[1]='b';
		alphabet[2]='c';
		alphabet[3]='d';
		alphabet[4]='e';
		alphabet[5]='f';
		alphabet[6]='g';
		alphabet[7]='h';
		alphabet[8]='i';
		alphabet[9]='j';
		alphabet[10]='k';
		alphabet[11]='l';
		alphabet[12]='m';
		alphabet[13]='n';
		alphabet[14]='o';
		alphabet[15]='p';
		alphabet[16]='q';
		alphabet[17]='r';
		alphabet[18]='s';
		alphabet[19]='t';
		alphabet[20]='u';
		alphabet[21]='v';
		alphabet[22]='w';
		alphabet[23]='x';
		alphabet[24]='y';
		alphabet[25]='z';
	}
	
	public void run()
	{	
		Scanner in = new Scanner(System.in);
		System.out.print("Would you like to play Hangman? " +
			"(type 'yes' for yes or 'no' for no)");
		String response=in.next();
		this.readDictionary();
		Random rand = new Random();
		while(response.equals("yes"))
		{			
			this.setup(rand);
			System.out.println(underscore);
			System.out.println(alphabet);
			while(containUnderscore()==false && numberWrong<7)
			{
								
				//what to put in here....
				//check to see if the game is over - this.endGame();								
			}			
			System.out.print("Would you like to play Hangman? " +
			"(type 'yes' for yes or 'no' for no");
			response=in.next();
		}	
			
	}	
	
	public static void main(String [] args)
	{
		Hangman game = new Hangman();
		game.run();
	}
}
YoungWinston
opfire6 wrote:
Well i looked it over again.. and I managed to switch up a lot of things. I however am still having problems with deleting the chosen letters from the array, filling in the underscores with the correct letter guessed, and with continuing to print out the list of letters left to guess for every guess. If anyone can help me out that would be great.
First of all, well done. This is starting to look like a program and you've clearly put some thought into it. You've got some good methods, and your variables are named nicely.

A few general points before I look into the nuts and bolts:

1. Avoid using numeric literals as constants. It almost always indicates that you've made an assumption that may not necessarily be true, and if it isn't, you'll have to change your program in several places to correct it. If it truly is a constant that has a meaning, give it a name (ie, make it a field, and make it final). In the case of 26, which you've used in several places, there is an even better alternative though:
alphabet.length
and similarly for 55:
dictionary.length
2. There is an alternative to removing guessed letters from your alphabet string (although I understand why you're doing it):
Set the letter to "null" instead.
Now I know there is no 'null' constant for a char, but there is an equivalent:- 0 (and I do mean 0, not '0').
A char is a numeric value, just like int or long, and it's perfectly legal to say 'char myChar = 0'. It's even called a NUL, and it is absolutely guaranteed NOT to be part of any alphabet.

The great advantage of doing it that way is that you don't need to compress your array every time, and any scan for a supplied letter will not match a 0 (a user can't enter NUL with a Scanner).

3. You really only need to set your dictionary and alphabet up once for any Hangman object. I'd suggest that the constructor might be the best place for this. If you wanted to get fancy, you could even put the alphabet in the dictionary. That way, you could offer the game in more than one language. Of course you'll then have to copy your alphabet into another array at the start of each game ('unguessedLetters' perhaps?).

Anyway, now to look at your code...

Winston

Edited by: YoungWinston on Apr 29, 2010 2:11 AM
YoungWinston
opfire6 wrote:
public void unguessed()
{
	Scanner in = new Scanner(System.in);
	int numLetters=26;
	System.out.print("Please enter a letter: ");
	String letter=in.next();
	char guess=letter.charAt(0);
	for(int index=0; index<numLetters-1; index++)
	{
		alphabet[index]=alphabet[index+1];
	}
	numLetters--;		
}
OK, this is a bit of a mess. First of all, you're combining the business of inputting a guess with validating it, and that's usually not good (and the same holds true for 'wrongGuess()' too). Methods should do one thing. Now that can be something quite big, like 'play game', but you should still be able to say what it does with a single verb.

And what does your 'for' loop do? I know what you want it to do, but what is it actually doing? Hint: where do you check if the letter in the array is the one in 'guess'?

As for printing out the letters left to guess, the easiest way (assuming you're still contracting the alphabet array every time) is to convert it to a string. Perhaps something like:
String.valueOf( Arrays.copyOf(alphabet, numLetters) );
opfire6 wrote:
while(containUnderscore()==false && numberWrong<7)
{
//what to put in here....
//check to see if the game is over - this.endGame();
}
I like the idea of a method that checks if the game is finished, but you're already checking for some of that in your 'while'.
What about
while(! this.gameFinished()) {
   ...
}
instead?
I'd also give a little bit more thought to the actual steps of the game. It might help you to sort out your methods a bit better.

HIH

Winston
1 - 8
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on May 27 2010
Added on Apr 27 2010
8 comments
2,055 views