Hi! I was wondering if someone could please help me with a hangman program that I have to do. I have some ideas, but really don't know what to do or where to start. My program needs to be: interactive with the user, menu based(like Menu: 1. Play hangman 2. Exit program), have a dictionaryand use a random method(create arrays of Strings or ListArray of Strings. e.g. : String [] dictionary =
“apple”, “ball”, “cat”, “dog”, …..} minimum words requirement is 200.), more than one method, and one method has to return a value. The final status of the game-8 failed attempts is a loss, each wrong answer should print this:(00)-<=< (hangman), notify the user of the loss and print the correct word, if the user guesses correctly the message should be “ You guessed it right,” and display the Menu again.

Here are my thoughts-
I think I should do a do/while loop like this:

int n;
boolean done = false;
do
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter your selection:\n 1. Play Hangman \n 2.Exit
program");
n = scan.nextInt();

if(n == 1)
{
//hangman program goes here and dictionary (dictionary[rand()%200])
}

if( n==2)
{
done = true;
}

}
while(! done);

System.out.print("GAME OVER");

Here are the 200 words I want to use:
"boy", "girl", "mother", "father", "sister", "love", "sky", "wind", "water", "study", "ball",
"cat", "dog", "puppy", "kitten", "apple", "pear", "lemon", "mango", "peach", "apricot", "chips", "steak", "fries", "cheese",
"patatoe", "wedge", "heel", "hand", "foot", "arm", "leg", "nose", "face", "mouth", "tongue", "fingers", "toes", "line", "space",
"phone", "cord", "core", "grass", "trees", "birds", "animals", "lazy", "funny", "king", "queen", "heart", "heat", "cold", "sun",
"moon", "movie", "theater", "hairy", "big", "small", "large", "huge", "pig", "donkey", "cow", "chicken", "pizza", "bread", "stones",
"sticks", "leaves", "letters", "alphabet", "soup", "hungry", "tired", "sleepy", "noisy", "caring", "friends", "month", "day", "light",
"toothbrush", "savings", "bank", "account", "teller", "paper", "pencil", "tea", "coffee", "spirit", "ghost", "can", "melon", "necklace",
"screen", "baloon", "string", "calendar", "work", "toys", "kids", "school", "class", "campus", "freedom", "liberty", "happiness",
"university", "message", "marker", "crayon", "eraser", "music", "lyrics", "songs", "ballads", "shapes", "triangle", "circle", "rectangle",
"square", "oval", "show", "video", "player", "team", "sport", "basketball", "football", "soccer", "softball", "baseball", "tennis",
"hockey", "lacrosse", "volleyball", "circut", "blade", "scratch", "hit", "home", "house", "safe", "safety", "number", "count", "bear",
"goose", "llama", "panda", "lion", "tiger", "cheetah", "computer", "crackers", "rice", "fan", "shoes", "book", "story", "princess",
"prince", "jester", "court", "jury", "judge", "bench", "scandal", "name", "newspaper", "press", "shove", "tear", "cry", "magic", "tricks",
"cereal", "breakfast", "lunch", "dinner", "main", "course", "fork", "spoon", "knife", "lamp", "desk", "bottle", "highlighter", "cap",
"medicine", "six", "seven", "flower", "rose", "petal"

I know my hangman program should start something like this, but I don't know where to go from here:
public Hangman()
{
misses = 0;
wordIndex = 0;
lettersUsed = new boolean[Character.MAX_VALUE];
}

private void clear()
{
int k;
for(k=0; k < Character.MAX_VALUE; k++) {
lettersUsed[k] = false;
}

Can someone please help me?

Thanks!

Recommended Answers

All 6 Replies

Member Avatar for iamthwee

Plan your code on paper first.

1. Read in a dictionary file and store the words in an arrayList.
2. Use the random function to pick a number from 0-Max_number_words, use this number as an index to pull out a word from the arrayList.
3. You'll need to keep tabs on the letters already guessed, and you need to figure out a way to chop a String into individuals characters.

Ok, so this is what I have so far and I want to use the private boolean contain method to:
1. letters guessed(like add a brand new letter thats wrong or right)
2. the guessed letter (the wrong letter)
3. if they guessed the letter before a statement that says "you guessed this already, please try again"
4. if they enter an invaild answer(like a number)

can someone please help me to do this?
(first file)

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;



public class HangManGame7
{


static String [] dictionary = new String[200];


static String word = "";
static ArrayList guesses = new ArrayList();
static ArrayList wrongLetters = new ArrayList();
static int numberOfTries = 0;
static String[] deadMan = {"(","0","0",")","-","<","=","<"};


public HangManGame7()
{
try
{
BufferedReader in = new BufferedReader(new FileReader("dictionary.txt"));
int i = 0;
while (i < 200)
{
dictionary[i++] = in.readLine();
}
in.close();
}
catch (IOException e)
{
System.err.println("Error: File failed to close");
}
}


public void play()
{
System.out.print("Let's play HANGMAN!\n");
System.out.println("Instructions: Enter a letter when asked. " +
"Try to guess the word in less than 8 tries to stop from being hanged! Good luck!\n\n");
word = dictionary[(int) (Math.random()%200)] ;
buildWord();
System.out.println("Word "+guesses);
System.out.println("Wrong letters "+wrongLetters);
System.out.println("Status ");
for (int i = 0; i < numberOfTries; i++)
{
System.out.println(deadMan);
}


}



/*public boolean contains(String s)
{
return word.contains(s);
}


private static void buildWord()
{
for (int i = 0 ; i < word.length(); i++)
{
guesses.add("-");
}
boolean done = false;


do
{


if(word.contains(s ) && numberOfTries<MISSES)
{
System.out.println("Word "+guesses);
System.out.println("Wrong letters "+wrongLetters);
System.out.println("Status ");
}
if(! word.contains(s) && numberOfTries<MISSES)
{
System.out.println("Word "+guesses);
System.out.println("Wrong letters "+wrongLetters);
System.out.println("Status ");
}
if(! word.contains(s) && numberOfTries==MISSES)
{
System.out.println("Word "+guesses);
System.out.println("Wrong letters "+wrongLetters);
System.out.println("Status ");
done = true;
}
}


while(! done);


}*/

(second file )

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



public class Main2
{
public static void main(String[] args) throws FileNotFoundException
{
int choice;
boolean done = false;
do
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter your selection:\n 1. Play Hangman \n 2. Exit program\n\n");
choice = scan.nextInt();


if(choice == 1)
{
HangManGame7 hmg = new HangManGame7();
hmg.play();


}
else if(choice == 2)
{
done = true;
}


}
while(!done);
System.out.print("GAME OVER");
}
}

and the dictionary.txt file i have

boy
girl
mother
father
sister
love
sky
wind
water
study
ball
cat
dog
puppy
kitten
apple
pear
lemon
mango
peach
apricot
chips
steak
fries
cheese
potatoes
wedge
heel
hand
foot
arm
leg
nose
face
mouth
tongue
fingers
toes
line
space
phone
cord
core
grass
trees
birds
animals
lazy
funny
king
queen
heart
heat
cold
sun
moon
movie
theater
hairy
big
small
large
huge
pig
donkey
cow
chicken
pizza
bread
stones
sticks
leaves
letters
alphabet
soup
hungry
tired
sleepy
noisy
caring
friends
month
day
light
toothbrush
savings
bank
account
teller
paper
pencil
tea
coffee
spirit
ghost
can
melon
necklace
screen
balloon
string
calendar
work
toys
kids
school
class
campus
freedom
liberty
happiness
university
message
marker
crayon
eraser
music
lyrics
songs
ballads
shapes
triangle
circle
rectangle
square
oval
show
video
player
team
sport
basketball
football
soccer
softball
baseball
tennis
hockey
lacrosse
volleyball
circuit
blade
scratch
hit
home
house
safe
safety
number
count
bear
goose
llama
panda
lion
tiger
cheetah
computer
crackers
rice
fan
shoes
book
story
princess
prince
jester
court
jury
judge
bench
scandal
name
newspaper
press
shove
tear
cry
magic
tricks
cereal
breakfast
lunch
dinner
main
course
fork
spoon
knife
lamp
desk
bottle
highlighter
cap
medicine
six
seven
flower
rose
petal
Member Avatar for iamthwee

ok i'll look at this later. For those who want to look at it now i've tagged your code up.

HangManGame7.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*; 
public class HangManGame7
{
 static String [] dictionary = new String[200]; 
 static String word = "";
 static ArrayList guesses = new ArrayList();
 static ArrayList wrongLetters = new ArrayList();
 static int numberOfTries = 0;
 static String[] deadMan =
 {"(", "0", "0", ")", "-", "<", "=", "<"};
 public HangManGame7()
 {
    try
    {
       BufferedReader in = new BufferedReader ( new FileReader ( "dictionary.txt" ) );
       int i = 0;
       while ( i < 200 )
       {
          dictionary[i++] = in.readLine();
       }
       in.close();
    }
    catch ( IOException e )
    {
       System.err.println ( "Error: File failed to close" );
    }
 }
 public void play()
 {
    System.out.print ( "Let's play HANGMAN!\n" );
    System.out.println ( "Instructions: Enter a letter when asked. " +
                         "Try to guess the word in less than 8 tries to stop from being hanged! Good luck!\n\n" );
    word = dictionary[ ( int ) ( Math.random() %200 ) ] ;
    buildWord();
    System.out.println ( "Word " + guesses );
    System.out.println ( "Wrong letters " + wrongLetters );
    System.out.println ( "Status " );
    for ( int i = 0; i < numberOfTries; i++ )
    {
       System.out.println ( deadMan[i] );
    }
 } 
 /*
public boolean contains ( String s )
{
  return word.contains ( s );
}
private static void buildWord()
{
  for ( int i = 0 ; i < word.length(); i++ )
  {
     guesses.add ( "-" );
  }
  boolean done = false;
  do
  {
     if ( word.contains ( s ) && numberOfTries < MISSES )
     {
        System.out.println ( "Word " + guesses );
        System.out.println ( "Wrong letters " + wrongLetters );
        System.out.println ( "Status " );
     }
     if ( ! word.contains ( s ) && numberOfTries < MISSES )
     {
        System.out.println ( "Word " + guesses );
        System.out.println ( "Wrong letters " + wrongLetters );
        System.out.println ( "Status " );
     }
     if ( ! word.contains ( s ) && numberOfTries == MISSES )
     {
        System.out.println ( "Word " + guesses );
        System.out.println ( "Wrong letters " + wrongLetters );
        System.out.println ( "Status " );
        done = true;
     }
  }
  while ( ! done );
}
*/

Main2.java

import java.io.FileNotFoundException;
import java.util.Scanner;
 
public class Main2
{
 public static void main ( String[] args ) throws FileNotFoundException
 {
    int choice;
    boolean done = false;
    do
    {
       Scanner scan = new Scanner ( System.in );
       System.out.print ( "Enter your selection:\n 1. Play Hangman \n 2. Exit program\n\n" );
       choice = scan.nextInt();
       if ( choice == 1 )
       {
          HangManGame7 hmg = new HangManGame7();
          hmg.play();
       }
       else if ( choice == 2 )
       {
          done = true;
       }
    }
    while ( !done );
    System.out.print ( "GAME OVER" );
 }
}

dictionary.txt

boy
girl
mother
father
sister
love
sky
wind
water
study
ball
cat
dog
puppy
kitten
apple
pear
lemon
mango
peach
apricot
chips
steak
fries
cheese
potatoes
wedge
heel
hand
foot
arm
leg
nose
face
mouth
tongue
fingers
toes
line
space
phone
cord
core
grass
trees
birds
animals
lazy
funny
king
queen
heart
heat
cold
sun
moon
movie
theater
hairy
big
small
large
huge
pig
donkey
cow
chicken
pizza
bread
stones
sticks
leaves
letters
alphabet
soup
hungry
tired
sleepy
noisy
caring
friends
month
day
light
toothbrush
savings
bank
account
teller
paper
pencil
tea
coffee
spirit
ghost
can
melon
necklace
screen
balloon
string
calendar
work
toys
kids
school
class
campus
freedom
liberty
happiness
university
message
marker
crayon
eraser
music
lyrics
songs
ballads
shapes
triangle
circle
rectangle
square
oval
show
video
player
team
sport
basketball
football
soccer
softball
baseball
tennis
hockey
lacrosse
volleyball
circuit
blade
scratch
hit
home
house
safe
safety
number
count
bear
goose
llama
panda
lion
tiger
cheetah
computer
crackers
rice
fan
shoes
book
story
princess
prince
jester
court
jury
judge
bench
scandal
name
newspaper
press
shove
tear
cry
magic
tricks
cereal
breakfast
lunch
dinner
main
course
fork
spoon
knife
lamp
desk
bottle
highlighter
cap
medicine
six
seven
flower
rose
petal
Member Avatar for iamthwee

OK, it looks like a good start. A few things.

while ( i < 200 )
{
dictionary[i++] = in.readLine();
}

That doesn't really make sense. It should be:

while ( i < 200 )
{
  dictionary[i] = in.readLine();
   System.out.println ( dictionary[i] );
   i++;
}

And your random function is wrong:

word = dictionary[ ( int ) ( Math.random() %200 ) ] ;
buildWord();
System.out.println ( "Word " + guesses );

It should be:

int k = ( int ) Math.floor ( Math.random() * 200  );
word = dictionary[ k ] ; 
System.out.println ( word  + " " + k ); //word has no quotes and has
//lower case 'w'

Try changing that first. When you have done that you will need to get that word find its length using the .length() function and split it into individual chars.

Looping through each char in a string

public class Test
{
   public static void main ( String[] args )
   {
      String crap = "Hello";
      //loop through each char
      for ( int i = 0; i < crap.length(); i++ )
      {
         System.out.println ( crap.substring ( i, i + 1 ) );
      }
   }
}

Thanks soooooo much for your help!!! i will try doing that and get back to you on how it goes!! But again THANK YOU!!!!!!!!!!!!!!!!!!

:P

Looping through each char in a string

public class Test
{
   public static void main ( String[] args )
   {
      String crap = "Hello";
      //loop through each char
      for ( int i = 0; i < crap.length(); i++ )
      {
         System.out.println ( crap.substring ( i, i + 1 ) );
      }
   }
}

Or better...

public class Test
{
   public static void main ( String[] args )
   {
      String crap = "Hello";
      //loop through each char
      for ( int i = 0, limit = crap.length(); i < limit; i++ )
      {
         System.out.println(crap.charAt(i));
      }
   }
}

- No need of calculating the length of the string for each iteration.
- A lighter function charAt() is much recommended if you only want characters rather than using the more generic substring() function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.