Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: JAVA HANGMAN PROGRAM

  1. #1
    Member
    Join Date
    Mar 2014
    Posts
    92
    My Mood
    Inspired
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default JAVA HANGMAN PROGRAM

    THIS IS THE QUESTION:
    The player must then guess a letter (ch, say). If ch is not in the word, the player is
    one step closer to being hanged. If ch is in the word, the string of *s is displayed
    with the letter ch replacing a * wherever it occurs in the word. For instance, if the
    player guesses e, the string is displayed as follows:
    * e * * e * *
    This procedure is repeated until the player guesses the word or he is hanged,
    whichever comes first. The player gets hanged if he makes a predetermined
    number (7, say) of unsuccessful guesses. Each time the player makes a guess, the
    computer will inform him of the word obtained so far and the number of wrong
    guesses he can still make before being hanged. A sample run might look like this
    (the underlined letters are typed by the player):
    Try to guess my secret word
    Countdown to hang: 7
    * * * * * * *
    Guess a letter: n
    Sorry, try again
    * * * * * * *
    Countdown to hang: 6
    Guess a letter: s
    s * * * * * s
    Countdown to hang: 6
    Guess a letter: r
    s * * r * * s
    Countdown to hang: 6
    Guess a letter: a
    Sorry, try again
    s * * r * * s
    Countdown to hang: 5
    Guess a letter: e
    s e * r e * s
    Countdown to hang: 5
    Guess a letter: d
    Sorry, try again
    s e * r e * s
    Countdown to hang: 4
    Guess a letter: t
    s e * r e t s
    Countdown to hang: 4
    Guess a letter: c
    s e c r e t s
    Countdown to hang: 4
    You've got it!!
    Write the program so that the computer chooses a word at random from a list of words stored in a file.



    THIS IS MY SOLUTION:
     
    import java.io.*;
    import java.util.Scanner;
     
    public class Test {
    	public static void main (String[] args) throws IOException { 
    	Scanner in = new Scanner(new FileReader("list.txt"));
    	//Declares variables
    	String word= " ";
        int misses = 0;
        int exposed = 0 ;
        String word= " ";
        int countdown = 7;
        char guess;
        boolean correctGuess= false;
        //char [] display = new char [10];
     
        for (int i = 0; i < display.length; i++)
        {
        	display[i] = "*";
        }
     
     
         System.out.printf("Try to guess my secret word");
         //System.out.printf("Countdown to hang: 7");
    	 while (exposed  < word.length())
    	 {
    		 System.out.printf ("Countdown to hang: ", countdown - misses);
    		 System.out.printf ("Enter a guess ");
    		 guess = in.read();
     
     
     
    	//Checks to see if letter guessed is correct
    	//Correct guess is true
    	 for (int i= 0; i < word.length(); i ++)
    	 {
     
    		 if (guess == word[i])
    		 {
    			 display [i] = word [i];
    			 exposed ++;
    			 correctGuess = true;
    		 }
     
    	 }
     
    	 //Correct guess is false
    	 if (!correctGuess)
    	 {
    		 misses++;
    		 countdown--;
    		 System.out.printf ("Sorry try again\n");
    	 }
     
    	}//end while
     
    	System.out.printf ("You've got it!");
            in.close();
    }	
    }


    MY PROBLEMS:
    I have problems declaring arrays>> how do i declare display and how to i declare word?
    I have problems reading a single character from a file>>>>how do i read the guess entered correctly?


    Please help me.
    Last edited by Java girl; April 13th, 2014 at 04:04 PM.


  2. #2
    Member
    Join Date
    Oct 2013
    Location
    Manila, Philippines
    Posts
    285
    My Mood
    Amused
    Thanks
    6
    Thanked 64 Times in 61 Posts

    Default Re: JAVA HANGMAN PROGRAM

    First, are the words in the file separated by carriage return (enter/newline) or separated by space?
    Second, do you know how many words does the file contains? If you know, you can use a simple array of String, otherwise you'll need a collections that varies the size of the array
    Third, have you successfully read the file? Because I didn't see any file reading statements in your code.
    Fourth, after reading it, do you have an idea on how to get a random word from array?

    Actually there is a reading statement from you code, but makes no sense since that statement is trying to read all the file content (per character I guess). I think it is better to solve your problem one by one so please answer my questions above so we won't get stuck in some bugs

  3. #3
    Member
    Join Date
    Mar 2014
    Posts
    92
    My Mood
    Inspired
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: JAVA HANGMAN PROGRAM

    1. In the file, each word is placed on a newline.
    2. No specified number of words were given.
    3. Yes there is a file reading, I see your logic on how its actually read, good point
    4.I actually didn't consider that fourth point while coding my solution. I can attempt a way to do so.

  4. #4
    Member
    Join Date
    Oct 2013
    Location
    Manila, Philippines
    Posts
    285
    My Mood
    Amused
    Thanks
    6
    Thanked 64 Times in 61 Posts

    Default Re: JAVA HANGMAN PROGRAM

    Okay, lets solve the first problem. Lets read the file first and store it array.
    Since you don't know how many words does the file has, we will use a collection. are you familiar with List? ArrayList? LinkedList?
    ArrayList (Java Platform SE 7 )
    LinkedList (Java Platform SE 7 )
    are you allowed to use ArrayList?

    I think it much better to use BufferedReader rathan than Scanner to read the file, do you know what is BufferedReader in java? the reason is, BufferedReader can determine if it reaches the end of file while scanner needs to throws a NoSuchElementException when it reaches the end of file.
    BufferedReader (Java Platform SE 7 )
    If not, it's ok, we will use the Scanner,

    --- Update ---

    Correction with First paragraph. About how many words does the file contain? if it is not so many and String class can handle it, I think it can hold by a String/StringBuilder class in java. so we don't need to use ArrayList.

  5. #5
    Member
    Join Date
    Mar 2014
    Posts
    92
    My Mood
    Inspired
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: JAVA HANGMAN PROGRAM

    Currently we only use scanner in class. I will read through the links and take all ur points into consideration to alter my current code. Will re-upload in an hour

  6. #6
    Member
    Join Date
    Oct 2013
    Location
    Manila, Philippines
    Posts
    285
    My Mood
    Amused
    Thanks
    6
    Thanked 64 Times in 61 Posts

    Default Re: JAVA HANGMAN PROGRAM

    Is it possible to program it in just reading a file? So you won't get stuck with other bugs?
    And please take a look at http://docs.oracle.com/javase/7/docs...l/Scanner.html in nextLine() method.
    it reads each line, so each reading will read each words. That is more appropriate function to use rather than read function.

  7. #7
    Member
    Join Date
    Mar 2014
    Posts
    92
    My Mood
    Inspired
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: JAVA HANGMAN PROGRAM

    I have to read the words from the file and output it onscreen

  8. #8
    Member
    Join Date
    Oct 2013
    Location
    Manila, Philippines
    Posts
    285
    My Mood
    Amused
    Thanks
    6
    Thanked 64 Times in 61 Posts

    Default Re: JAVA HANGMAN PROGRAM

    did you successfully read the file? and print it?
    please paste your code here. so I can guide you.

  9. #9
    Member
    Join Date
    Mar 2014
    Posts
    92
    My Mood
    Inspired
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: JAVA HANGMAN PROGRAM

    Sorry, not done yet, am actually multitasking with another assignment due tonight. Will upload as soon as am finished.

  10. #10
    Member
    Join Date
    Mar 2014
    Posts
    92
    My Mood
    Inspired
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: JAVA HANGMAN PROGRAM

    I am having a lot of difficulties so I attempted to get away to find the random number:

     strWordArray = new String[10];
     
        for (int i = 0; i < strWordArray.length; i++) {
            strWordArray[i] = br.readLine();
            System.out.println(strWordArray[i]);
        }
        wordsFile.close();
     
    Random rand = new Random();
     
        for (int i = 0; i < strWordArray.length; i++) {
            int intWord = rand.nextInt(6) + 1;
            word = new StringBuffer(strWordArray[i]);
     
        }


    The first part should load the text file into an array and the second part should get the random word out from the array.
    I am not allowed to use string buffer, this is an attempt based on everything i have tried, I am trying to understand the logic of getting a random number from the file.

  11. #11
    Member
    Join Date
    Oct 2013
    Location
    Manila, Philippines
    Posts
    285
    My Mood
    Amused
    Thanks
    6
    Thanked 64 Times in 61 Posts

    Default Re: JAVA HANGMAN PROGRAM

    strWordArray = new String[10];
    so only 10 words will be get from the file? how about it is more than 10 words?

    word = new StringBuffer(strWordArray[i]);
    what is word? it is not declared? do you got an error?

    The first part should load the text file into an array and the second part should get the random word out from the array.
    so you don't need the loop just by getting a random word.

    int intWord = rand.nextInt(6) + 1;
    the perfect way to get a random word from a string array is to pass its length.
    rand.nextInt(length of the array);
    it will generate a random numbers from 0 to array's length - 1

  12. #12
    Member
    Join Date
    Mar 2014
    Posts
    92
    My Mood
    Inspired
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: JAVA HANGMAN PROGRAM

    Sigh, I retried the entire code but I am uncertain about the section of checking for a match and getting the random word is still confusing.

     
     
    import java.util.*;
     
    public class Test3 {
        public static void main( String[] args){ 
        	Random r;
        	//int GetData get;
        	String [] words ={" marsh","swamp" ,"mountain", "pensinsula"};
        	String word;// to hold the chosen word
        	boolean finished = false;
        	int badGuessCount = 0;//tracks number of guesses
        	boolean [] foundLetters;// boolean array to track which letters have been found
        	String  entryWord = " ";//user guesses
     
     
        	//Gets random word
     
     
     
     
     
        	//get = new getData();
     
     
        	//Start of game: 
        	//choose a word from the list of words
        	word = words[r.nextInt(words.length)];
        	//create a boolean array the size of the word
        	foundLetters = new boolean [word.length()];
     
        	while(!finished)
        	{
        		//Shows words
        		boolean goodGuess=false;
        		char ch = entryWord.charAt(0);
        		for (int i = 0; i< word.length(); i++)
        		{
        			if (foundLetters[i] == true)
        			{
        				System.out.printf(word.charAt(i) +" " );
        			}
        			else if (word.charAt(i) == ch)
        			{
        				System.out.printf(word.charAt(i) +" " );
        				foundLetters[i] = true;
        				goodGuess= true;	
        			}
        			else
        			{
        				System.out.printf("*");
        			}			
        		}//end for loop
     
     
     
        		//Gets guess
        		System.out.println("What is your guess");
        		System.out.println("You have " + (7-badGuessCount) + " guesses left");
        		System.out.println("Enteryour guess");
     
        		//Checks guess
        		 char temp=' ';
        		 int len =word.length();
        		 int foundPos = -2;
                 int foundCount = 0; //How many matches did we find
                 while((foundPos = word.indexOf(entryWord.charAt(0), foundPos + 1)) != -1)
                 {
                     temp[foundPos] = entryWord.charAt(0); //Update the temp array from * to the correct character
                     foundCount++;
                     len--; //Decrease overall counter
                 }
        		if (badGuessCount==7)
                {
                    System.out.println("Sorry, but you lost.");
                    System.out.println("The word was: "+word);
                    finished=true;
                }
     
        	}//end while 	
     
        }
    }

    The more I try to get the whole logic of the program, some places I am still confused.
    Last edited by Java girl; April 13th, 2014 at 04:05 PM.

  13. #13
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: JAVA HANGMAN PROGRAM

    To help you it's essential to understand your confusion. The code you posted has a blank area where the word is to be chosen randomly, so instead of confusion we see lack of effort.

    Choosing the random word is similar to the "Guess what I'm thinking" method of choosing a winner. If I told you, "I'm thinking of a number between 0 and 10. The closes guess gets a piece of cake," you'd guess a number bewteen 0 and 10. In this program, you have 4 words numbered 0 through 3 according to their array index. Your task is to use Java to pick a random number between 0 and 3, inclusive, to determine which number to use. As dicdic explained, the way to do that is to use the Random.nextInt() method (<-- click to read API doc).

    Review the advice you've been given and try to write the code needed to select a random number between 0 and 3, inclusive. Once you've done that, selecting the word is easy.

Similar Threads

  1. [SOLVED] Hangman Program Java: Comparing the User's Guess with Another String Letter by Letter
    By theonlydvr in forum What's Wrong With My Code?
    Replies: 4
    Last Post: June 29th, 2013, 05:35 PM
  2. Hangman Program for CP1
    By MaddestHatter13. in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 9th, 2013, 02:15 PM
  3. Java Hangman program! Need help reading an ar
    By mmagyar14 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: January 16th, 2013, 03:18 AM
  4. Hangman program
    By psgtyler in forum What's Wrong With My Code?
    Replies: 1
    Last Post: January 5th, 2013, 12:58 AM
  5. Need help with my hangman program!
    By mbae in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 29th, 2012, 07:24 PM