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 25 of 25

Thread: Java hangman help with comparing array to String

  1. #1
    Member
    Join Date
    Jul 2013
    Location
    Baltimore, MD
    Posts
    59
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Java hangman help with comparing array to String

    I'm trying to figure out how to let the dash[] know the player entered all the correct letters to solve the game. It knows the correct word was guessed, the first part of the if condition word.equals(guess) , but the second part dashArray[b].equals(word.charAt(b)) doesn't work, that's what I need help with. I know the counter doesn't work now, but I'll work on that after I figure this out.

    Basically, my random word for now is "elephant" for testing purposes.

    so if I type "elephant" any time, the game ends, but if I type, e, l, p, h, a, n, t it doesn't know, the game is done even though all the letters are correctly guessed.

    This is the part of the code I'm having trouble with:

    if(word.equals(guess) || dashArray[b].equals(word.charAt(b)))  // currently working on this, make an array to store guesses?
                    {
                        dashArray[b] = "" + guess.charAt(b);  
     
                        hanged = true;
                    }

    This is the full code:

    package hangmangame;
     
    /*
     * STEPS TO WRIE HANGMAN PROGRAM (Hangman game pseudocode)
     * -------------------------------------------------------
     * 1.  Create an array with some words
     * 2.  Create an empty dashArray
     * 3.  Create an alphabet array to delete used letters
     * 4.  Get a random word from the word array using random number generator
     * 5.  Set the word to the random number's index from the word array
     * 6.  Create a new dash array with the number of letters in the word
     * 7.  Get a guess from user
     * 8.  Check if the guess is in the word
     * 9.  If yes, replace the dash with the correct letter
     * 10. Delete the letter from alphabet array (good or bad)
     * 11. If the correct word is guessed, show the word and says you win
     * 12. If the incorrect word is guessed, only take the first character of the word, and put it in the correct place
     * 13. Create a counter to count each time the wrong guess is entered
     * 14. Display the appropriate "hangman" image
     * 15. If the counter is more than six, the player fails (hangman hanged)
     * 
     *     Need to figure out the counter to display each hangman sequence
     */
     
    import java.util.Random;
    import java.util.Scanner;
     
    public class HangmanGame {
     
        public static void main(String[] args) {
     
            Random rand = new Random();
            Scanner scan = new Scanner(System.in);
     
            String word, guess;
            char check;
            int random = 0, counter = 0;
            boolean hanged = false;
     
            String[] alphabetArray = {" A ", " B ", " C ", " D ", " E ", " F ", " G ", " H ", " I ", " J ", " K ", " L ", " M ",
                                                   " N ", " 0 ", " P ", " Q ", " R ", " S ", " T ", " U ", " V ", " W ", " X ", " Y ", " Z "};
     
            String[] wordsArray = {"elephant"};
     
            /*
             *                                  , "star", " candy", "wings", "shopping", "steak", "couch", "toy", "cat", "mouse",
                                                "elevator", "taxi", "airplane", "bus", "car", "flower", "cheese", "apple", "orange", "coat",
                                                "running", "sweater", "blanket", "chocolate", "chicken", "computer", "rice", "dance", "doll",
                                                "duck", "alligator", "snake", "calculator", "castle", "balloon", "laptop", "turtle", "pencil",
                                                "fridge", "police", "antartica", "dinner", "fire", "cookie", "pizza", "church", "village"
     
     
             */
     
            String[] dashArray;
     
            random = rand.nextInt(wordsArray.length);
            word = wordsArray[random];
            dashArray = new String[word.length()];   
     
            System.out.println("------------------: HANGMAN GAME INSTRUCTIONS :------------------");
            System.out.println("1. You can enter either a letter or try to guess the word any time.");
            System.out.println("2. You have six chances before the hangman is hanged (you fail).");
            System.out.println("3. If you try to guess the word, but the guess is wrong, program will read the first letter only");
            System.out.println("4. If you guess the word correctly, you win");
     
            System.out.println("\t\t\t\t\t _____");
            System.out.println("\t\t\t\t\t |   |");
            System.out.println("\t\t\t\t\t     |");
            System.out.println("\t\t\t\t\t     |");
            System.out.println("\t\t\t\t\t     |");
            System.out.println("\t\t\t\t\t_____|");
     
     
            System.out.print("Letters available: ");
     
            for(int c=0; c<alphabetArray.length; c++)
            {
                System.out.print(alphabetArray[c]);
            }
     
            System.out.println();
     
            for(int a=0; a<dashArray.length; a++)
            {
                dashArray[a] = " - ";
                System.out.print(dashArray[a]);           
            }
     
            while(hanged == false)
            {        
                System.out.println();
     
                System.out.print("Enter a guess (letter or word): ");
                guess = scan.nextLine();
                check = guess.charAt(0);
     
                for(int b=0; b<dashArray.length; b++)
                {
                    if(check == word.charAt(b))                    
                    {                    
     
                        alphabetArray[(int) Character.toUpperCase(check) - 65] = " ";
     
                        dashArray[b] = "" + guess.charAt(0);
     
                        dashArray[word.indexOf(guess.charAt(0))] = "" + check;
     
                        hanged = false;
                    }
     
                    else
                    {
                        alphabetArray[(int) Character.toUpperCase(check) - 65] = " ";
     
                        hanged = false;
                    }
     
                    if(word.equals(guess) || dashArray[b].equals(word.charAt(b)))  // currently working on this, make an array to store guesses?
                    {
                        dashArray[b] = "" + guess.charAt(b);  
     
                        hanged = true;
                    }  
     
                        System.out.print(dashArray[b]);   
                }  
     
                System.out.println();   
     
                if(counter == 1)  
                {
                    System.out.println("\t\t\t\t\t _____");
                    System.out.println("\t\t\t\t\t |   |");
                    System.out.println("\t\t\t\t\t 0   |");
                    System.out.println("\t\t\t\t\t     |");
                    System.out.println("\t\t\t\t\t     |");
                    System.out.println("\t\t\t\t\t_____|");
                    hanged = false;
                }
     
                else if(counter == 2)
                {
                    System.out.println("\t\t\t\t\t _____");
                    System.out.println("\t\t\t\t\t |   |");
                    System.out.println("\t\t\t\t\t 0   |");
                    System.out.println("\t\t\t\t\t |   |");
                    System.out.println("\t\t\t\t\t     |");
                    System.out.println("\t\t\t\t\t_____|");
                    hanged = false;                
                }
     
                else if(counter == 3)
                {
                    System.out.println("\t\t\t\t\t _____");
                    System.out.println("\t\t\t\t\t |   |");
                    System.out.println("\t\t\t\t\t 0   |");
                    System.out.println("\t\t\t\t\t/|   |");
                    System.out.println("\t\t\t\t\t     |");
                    System.out.println("\t\t\t\t\t_____|");
                    hanged = false;                
                }
     
                else if(counter == 4)
                {                
                    System.out.println("\t\t\t\t\t _____");
                    System.out.println("\t\t\t\t\t |   |");
                    System.out.println("\t\t\t\t\t 0   |");
                    System.out.println("\t\t\t\t\t/|\\  |");
                    System.out.println("\t\t\t\t\t     |");
                    System.out.println("\t\t\t\t\t_____|");
                    hanged = false; 
     
                }
     
                else if(counter == 5)
                {
                    System.out.println("\t\t\t\t\t _____");
                    System.out.println("\t\t\t\t\t |   |");
                    System.out.println("\t\t\t\t\t 0   |");
                    System.out.println("\t\t\t\t\t/|\\  |");
                    System.out.println("\t\t\t\t\t/    |");
                    System.out.println("\t\t\t\t\t_____|");
                    hanged = false;                 
                }
     
                else if(counter == 6)
                {
                    System.out.println("\t\t\t\t\t _____");
                    System.out.println("\t\t\t\t\t |   |");
                    System.out.println("\t\t\t\t\t 0   |");
                    System.out.println("\t\t\t\t\t/|\\  |");
                    System.out.println("\t\t\t\t\t/ \\  |");
                    System.out.println("\t\t\t\t\t_____|");
                    hanged = false;                    
                }
     
                if(counter > 6)
                {
                    System.out.println("The word was: " + word);
                    hanged = true;                
                }
     
                if(hanged == true)
                {
                    System.out.println("Good guess, you win!");
                }
     
                System.out.println();
     
                System.out.print("Letters available: ");
     
                for(int d=0; d<alphabetArray.length; d++)
                {                         
                    switch (guess) 
                    {
                        case "a":
                            alphabetArray[0] = " ";
                            break;
                        case "b":
                            alphabetArray[1] = " ";
                            break;
                        case "c":
                            alphabetArray[2] = " ";
                            break;
                        case "d":
                            alphabetArray[3] = " ";
                            break;
                        case "e":
                            alphabetArray[4] = " ";
                            break;
                        case "f":
                            alphabetArray[5] = " ";
                            break;
                        case "g":
                            alphabetArray[6] = " ";
                            break;
                        case "h":
                            alphabetArray[7] = " ";
                            break;
                        case "i":
                            alphabetArray[8] = " ";
                            break;
                        case "j":
                            alphabetArray[9] = " ";
                            break;
                        case "k":
                            alphabetArray[10] = " ";
                            break;
                        case "l":
                            alphabetArray[11] = " ";
                            break;
                        case "m":
                            alphabetArray[12] = " ";
                            break;
                        case "n":
                            alphabetArray[13] = " ";
                            break;
                        case "o":
                            alphabetArray[14] = " ";
                            break;
                        case "p":
                            alphabetArray[15] = " ";
                            break;
                        case "q":
                            alphabetArray[16] = " ";
                            break;
                        case "r":
                            alphabetArray[17] = " ";
                            break;
                        case "s":
                            alphabetArray[18] = " ";
                            break;
                        case "t":
                            alphabetArray[19] = " ";
                            break;
                        case "u":
                            alphabetArray[20] = " ";
                            break;
                        case "v":
                            alphabetArray[21] = " ";
                            break;
                        case "w":
                            alphabetArray[22] = " ";
                            break;
                        case "x":
                            alphabetArray[23] = " ";
                            break;
                        case "y":
                            alphabetArray[24] = " ";
                            break;
                        case "z":
                            alphabetArray[25] = " ";
                            break;
                    }
     
                   System.out.print(alphabetArray[d]);
                }
            }  
        }
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Java hangman help with comparing array to String

    dashArray[b].equals(word.charAt(b)) doesn't work,
    What are the values of dashArray[b] and word.charAt(b) when it doesn't work?
    One possible problem is that dishArray holds String values and charAt() returns a char.

    Also posted at: Hangman game help, how to check if an array's index values matches with a String? - Dev Shed
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Jul 2013
    Location
    Baltimore, MD
    Posts
    59
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Java hangman help with comparing array to String

    Quote Originally Posted by Norm View Post
    What are the values of dashArray[b] and word.charAt(b) when it doesn't work?
    One possible problem is that dishArray holds String values and charAt() returns a char.

    Also posted at: Hangman game help, how to check if an array's index values matches with a String? - Dev Shed
    I did a system.out to see the actual values each time, and as you can see, even when dash[b] = elephant, and the word.charAt(b) matches it, it's still waiting for me to enter something instead of stopping the loop.

    run:
    --------
    Enter guess: e
    dash[b] e word.charAt(b) e
    dash[b] - word.charAt(b) l
    dash[b] e word.charAt(b) e
    dash[b] - word.charAt(b) p
    dash[b] - word.charAt(b) h
    dash[b] - word.charAt(b) a
    dash[b] - word.charAt(b) n
    dash[b] - word.charAt(b) t
     
    Enter guess: l
    dash[b] e word.charAt(b) e
    dash[b] l word.charAt(b) l
    dash[b] e word.charAt(b) e
    dash[b] - word.charAt(b) p
    dash[b] - word.charAt(b) h
    dash[b] - word.charAt(b) a
    dash[b] - word.charAt(b) n
    dash[b] - word.charAt(b) t
     
    Enter guess: p
    dash[b] e word.charAt(b) e
    dash[b] l word.charAt(b) l
    dash[b] e word.charAt(b) e
    dash[b] p word.charAt(b) p
    dash[b] - word.charAt(b) h
    dash[b] - word.charAt(b) a
    dash[b] - word.charAt(b) n
    dash[b] - word.charAt(b) t
     
    Enter guess: h
    dash[b] e word.charAt(b) e
    dash[b] l word.charAt(b) l
    dash[b] e word.charAt(b) e
    dash[b] p word.charAt(b) p
    dash[b] h word.charAt(b) h
    dash[b] - word.charAt(b) a
    dash[b] - word.charAt(b) n
    dash[b] - word.charAt(b) t
     
    Enter guess: a
    dash[b] e word.charAt(b) e
    dash[b] l word.charAt(b) l
    dash[b] e word.charAt(b) e
    dash[b] p word.charAt(b) p
    dash[b] h word.charAt(b) h
    dash[b] a word.charAt(b) a
    dash[b] - word.charAt(b) n
    dash[b] - word.charAt(b) t
     
    Enter guess: n
    dash[b] e word.charAt(b) e
    dash[b] l word.charAt(b) l
    dash[b] e word.charAt(b) e
    dash[b] p word.charAt(b) p
    dash[b] h word.charAt(b) h
    dash[b] a word.charAt(b) a
    dash[b] n word.charAt(b) n
    dash[b] - word.charAt(b) t
     
    Enter guess: t
    dash[b] e word.charAt(b) e
    dash[b] l word.charAt(b) l
    dash[b] e word.charAt(b) e
    dash[b] p word.charAt(b) p
    dash[b] h word.charAt(b) h
    dash[b] a word.charAt(b) a
    dash[b] n word.charAt(b) n
    dash[b] t word.charAt(b) t
     
    Enter guess:

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Java hangman help with comparing array to String

    A String and a char should never return true with the equals() method.
    Can you make dashArray a char array
    or use charAt(0) with the String in dashArray to get a char value to compare with ==?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Jul 2013
    Location
    Baltimore, MD
    Posts
    59
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Java hangman help with comparing array to String

    Quote Originally Posted by Norm View Post
    A String and a char should never return true with the equals() method.
    Can you make dashArray a char array
    or use charAt(0) with the String in dashArray to get a char value to compare with ==?
    [B]dashArray == (word.charAt(b) I tried to do it like that, but it's giving me a syntax error, so I can't compile it.

    [B]" " + dashArray == ("" + word.charAt(b) I tried this way, compiles but, still same problem, even after I guess "elephant" buy entering one letter at a time

    I've made the dashArray to a char array, like you said, now what should I do?

    --- Update ---

    This is the code with dash[] turned to a char array.

    package test;
     
    import java.util.Arrays;
    import java.util.Scanner;
    import java.util.Random;
     
    public class Test {
     
        public static void main(String[] args) {
     
            Scanner scan = new Scanner(System.in);
            Random rand = new Random();
     
            int r;        
            String[] words = {"elephant"};
            char[] dash;
     
            String guess, word;
            char check;
            boolean hanged = false;
            int counter = 0;
     
            r = rand.nextInt(words.length);
            word = words[r];
            dash = new char[word.length()];
     
            for(int a=0; a<dash.length; a++)
            {
                dash[a] = '-';
                System.out.print(dash[a]);
            }
     
            while(hanged == false)
            {
     
            System.out.println();
     
     
     
            System.out.print("Enter guess: ");
            guess = scan.nextLine();
            check = guess.charAt(0);
     
            for(int b=0; b<dash.length; b++)
            {            
                if(check == word.charAt(b))                    
                    {                    
     
                        dash[b] = guess.charAt(0);
     
                        dash[word.indexOf(guess.charAt(0))] = check;
     
                        hanged = false;
                    }
     
                    else
                    {              
     
                        hanged = false;
                    }
     
                    if(word.equals(guess))// currently working on this, make an array to store guesses?
                    {
                        dash[b] = guess.charAt(b);  
     
                        hanged = true;
                    }  
     
    //                System.out.println("dash[b] " + dash[b] +" word.charAt(b) " + word.charAt(b));
     
                        System.out.print(dash[b]);   
            }
     
     
     
            }
     
        }
    }

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Java hangman help with comparing array to String

    if dashArray is a char array, then you can use the == operator to compare an element to a char:
    if(dashArray[ix] == someChar) { ...

    When you get compiler errors, copy the full text of the error message and post it here in code tags to preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Jul 2013
    Location
    Baltimore, MD
    Posts
    59
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Java hangman help with comparing array to String

    This is the code with compiler error:

    package test;
     
    import java.util.Arrays;
    import java.util.Scanner;
    import java.util.Random;
     
    public class Test {
     
        public static void main(String[] args) {
     
            Scanner scan = new Scanner(System.in);
            Random rand = new Random();
     
            int r;        
            String[] words = {"elephant"};
            char[] dash;
     
            String guess, word;
            char check;
            boolean hanged = false;
            int counter = 0;
     
            r = rand.nextInt(words.length);
            word = words[r];
            dash = new char[word.length()];
     
            for(int a=0; a<dash.length; a++)
            {
                dash[a] = '-';
                System.out.print(dash[a]);
            }
     
            while(hanged == false)
            {
     
            System.out.println();
     
     
     
            System.out.print("Enter guess: ");
            guess = scan.nextLine();
            check = guess.charAt(0);
     
            for(int b=0; b<dash.length; b++)
            {            
                if(check == word.charAt(b))                    
                    {                    
     
                        dash[b] = guess.charAt(0);
     
                        dash[word.indexOf(guess.charAt(0))] = check;
     
                        hanged = false;
                    }
     
                    else
                    {              
     
                        hanged = false;
                    }
     
                    if(word.equals(guess) || word.charAt(b) == dash[b])// currently working on this, make an array to store guesses?
                    {
                        dash[b] = guess.charAt(b);  
     
                        hanged = true;
                    }  
     
    //                System.out.println("dash[b] " + dash[b] +" word.charAt(b) " + word.charAt(b));
     
                        System.out.print(dash[b]);   
            }
     
     
     
            }
     
        }
    }

    run:
    --------
    Enter guess: e
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    e-	at java.lang.String.charAt(String.java:658)
    	at test.Test.main(Test.java:64)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 1 second)

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Java hangman help with comparing array to String

    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    e- at java.lang.String.charAt(String.java:658)
    at test.Test.main(Test.java:64)
    That is NOT a compiler error. That error is when the code is executed.
    The code at line 64 uses an index value that is past the end of the String. A String of length 2 does not have a char at index 2. The valid indexes for a 2 char String would be 0 & 1.

    --- Update ---

    One thing that looks out of place is to compare word to guess every time the loop goes around.
    It should be test one time outside of the loop.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Member
    Join Date
    Jul 2013
    Location
    Baltimore, MD
    Posts
    59
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Java hangman help with comparing array to String

    So what should I do to fix it?

    I don't understand what I'm doing wrong. Logically, I'm comparing each index of dash[] with word.charAt(b), so it should work.

    --- Update ---

    Quote Originally Posted by Norm View Post
    One thing that looks out of place is to compare word to guess every time the loop goes around.
    It should be test one time outside of the loop.
    I've put if(word.equals(guess)) outside of the loop like you said, I compiled it, and works fine.

    package test;
     
    import java.util.Arrays;
    import java.util.Scanner;
    import java.util.Random;
     
    public class Test {
     
        public static void main(String[] args) {
     
            Scanner scan = new Scanner(System.in);
            Random rand = new Random();
     
            int r;        
            String[] words = {"elephant"};
            char[] dash;
     
            String guess, word;
            char check;
            boolean hanged = false;
            int counter = 0;
     
            r = rand.nextInt(words.length);
            word = words[r];
            dash = new char[word.length()];
     
            for(int a=0; a<dash.length; a++)
            {
                dash[a] = '-';
                System.out.print(dash[a]);
            }
     
            while(hanged == false)
            {
     
            System.out.println();
     
     
     
            System.out.print("Enter guess: ");
            guess = scan.nextLine();
            check = guess.charAt(0);
     
            for(int b=0; b<dash.length; b++)
            {            
                if(check == word.charAt(b))                    
                    {                    
     
                        dash[b] = guess.charAt(0);
     
                        dash[word.indexOf(guess.charAt(0))] = check;
     
                        hanged = false;
                    }
     
                    else
                    {              
     
                        hanged = false;
                    }
     
    //                if(word.charAt(b) == dash[b])// currently working on this, make an array to store guesses?
    //                {
    //                    dash[b] = guess.charAt(b);  
    //                   
    //                    hanged = true;
    //                }  
     
    //                System.out.println("dash[b] " + dash[b] +" word.charAt(b) " + word.charAt(b));
     
                        System.out.print(dash[b]);   
            }
     
            if(word.equals(guess))
            {
                hanged = true;
            }
     
     
     
            }
     
        }
    }

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Java hangman help with comparing array to String

    works fine.
    Does that mean you have solved your problem?
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Member
    Join Date
    Jul 2013
    Location
    Baltimore, MD
    Posts
    59
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Java hangman help with comparing array to String

    Quote Originally Posted by Norm View Post
    Does that mean you have solved your problem?
    What I meant was, moving the if condition outside of the for loop did the same thing.

    No sir, I'm sorry. I still have the original problem.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Java hangman help with comparing array to String

    Did you look at line 64 to see why the code is using an index value that is past the end of the String?
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Member
    Join Date
    Jul 2013
    Location
    Baltimore, MD
    Posts
    59
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Java hangman help with comparing array to String

    Quote Originally Posted by Norm View Post
    Did you look at line 64 to see why the code is using an index value that is past the end of the String?
    I did look, but I can't figure out what's going on.

    --- Update ---

    I have Java class tomorrow, and I'll ask my professor to look at my code if I can't figure it out.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Java hangman help with comparing array to String

    Post the code on line 64.

    Try debugging the code on line 64 by adding a println just before it that prints out the length of the String, the value of the String and the value of the index. The print out will show you what the problem is.

    This would give that same error:
    "abc".charAt(3)
    The max index is 2
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Member
    Join Date
    Jul 2013
    Location
    Baltimore, MD
    Posts
    59
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Java hangman help with comparing array to String

    I've made some modification.

                    if(word.charAt(b) == dash[b])// currently working on this, make an array to store guesses?
                    {
    //                    dash[b] = guess.charAt(b);  
     
                        hanged = true;
                    }

    Now the problem is, it's only looking to see if the last index of dash[b] and word.charAt(b), so if I just enter 't' with out anything else, it thinks the word is solved.

    run:
    --------
    Enter guess: t
    -------tBUILD SUCCESSFUL (total time: 2 seconds)






    package test;
     
    import java.util.Arrays;
    import java.util.Scanner;
    import java.util.Random;
     
    public class Test {
     
        public static void main(String[] args) {
     
            Scanner scan = new Scanner(System.in);
            Random rand = new Random();
     
            int r;        
            String[] words = {"elephant"};
            char[] dash;
     
            String guess, word;
            char check;
            boolean hanged = false;
            int counter = 0;
     
            r = rand.nextInt(words.length);
            word = words[r];
            dash = new char[word.length()];
     
            for(int a=0; a<dash.length; a++)
            {
                dash[a] = '-';
                System.out.print(dash[a]);
            }
     
            while(hanged == false)
            {
     
            System.out.println();
     
     
     
            System.out.print("Enter guess: ");
            guess = scan.nextLine();
            check = guess.charAt(0);
     
            for(int b=0; b<dash.length; b++)
            {            
                if(check == word.charAt(b))                    
                    {                    
     
                        dash[b] = guess.charAt(0);
     
                        dash[word.indexOf(guess.charAt(0))] = check;
     
                        hanged = false;
                    }
     
                    else
                    {              
     
                        hanged = false;
                    }
     
    //            System.out.println("dash[b] " + dash[b] +" word.charAt(b) " + word.charAt(b));
     
                    if(word.charAt(b) == dash[b])// currently working on this, make an array to store guesses?
                    {
    //                    dash[b] = guess.charAt(b);  
     
                        hanged = true;
                    }  
     
     
     
                        System.out.print(dash[b]);   
            }
     
            if(word.equals(guess))
            {
                hanged = true;
            }
     
     
     
            }
     
        }
    }


    --- Update ---

    I did a system.out to see the values, but as you can see as soon as I type 't' it exits loop, even though the word is not correct

    run:
    --------
    Enter guess: e
    dash[b] e word.charAt(b) e
    dash[b] - word.charAt(b) l
    dash[b] e word.charAt(b) e
    dash[b] - word.charAt(b) p
    dash[b] - word.charAt(b) h
    dash[b] - word.charAt(b) a
    dash[b] - word.charAt(b) n
    dash[b] - word.charAt(b) t
     
    Enter guess: l
    dash[b] e word.charAt(b) e
    dash[b] l word.charAt(b) l
    dash[b] e word.charAt(b) e
    dash[b] - word.charAt(b) p
    dash[b] - word.charAt(b) h
    dash[b] - word.charAt(b) a
    dash[b] - word.charAt(b) n
    dash[b] - word.charAt(b) t
     
    Enter guess: p
    dash[b] e word.charAt(b) e
    dash[b] l word.charAt(b) l
    dash[b] e word.charAt(b) e
    dash[b] p word.charAt(b) p
    dash[b] - word.charAt(b) h
    dash[b] - word.charAt(b) a
    dash[b] - word.charAt(b) n
    dash[b] - word.charAt(b) t
     
    Enter guess: t
    dash[b] e word.charAt(b) e
    dash[b] l word.charAt(b) l
    dash[b] e word.charAt(b) e
    dash[b] p word.charAt(b) p
    dash[b] - word.charAt(b) h
    dash[b] - word.charAt(b) a
    dash[b] - word.charAt(b) n
    dash[b] t word.charAt(b) t
    BUILD SUCCESSFUL (total time: 6 seconds)

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Java hangman help with comparing array to String

    it thinks the word is solved.
    When should the hanged variable be set to true?
    The code looks like it sets hanged true when ONE character matches.
    Shouldn't all the characters have been matched before hanged is set true?

    You need to stop writing code and do some design work so you have a list of steps the program should take to solve the problem. It looks like you are sort of randomly making changes here and there without any design.

    For example what are these two statements supposed to do:
          dash[b] = guess.charAt(0);
     
          dash[word.indexOf(guess.charAt(0))] = check;
    It looks like they are both changing the contents of dash.


    Also why is guess.charAt(0) used in one place and check in another.
    Aren't they the same value?
           check = guess.charAt(0);
    That shows confusion on what the code is doing.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Member
    Join Date
    Jul 2013
    Location
    Baltimore, MD
    Posts
    59
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Java hangman help with comparing array to String

    Sir, thanks for your help so far. I have to go to class now, so I'll let you know if I figure something out.

    Tony

  18. #18
    Member
    Join Date
    Jul 2013
    Location
    Baltimore, MD
    Posts
    59
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Java hangman help with comparing array to String

    Solved

    Java Platform SE 7

    Here's the working code, what I did was, I converted the char dash[] into a new String (test), and just compared two string with .equals(). Now time to work on the counter to display each stages of hangman.

    package test;
     
    import java.util.Scanner;
    import java.util.Random;
     
    public class Test {
     
        public static void main(String[] args) {
     
            Scanner scan = new Scanner(System.in);
            Random rand = new Random();
     
            int r;        
            String[] words = {"elephant"};
            char[] dash;
     
            String guess, word, test;
            char check;
            boolean hanged = false;
            int counter = 0;
     
            r = rand.nextInt(words.length);
            word = words[r];
            dash = new char[word.length()];
     
            for(int a=0; a<dash.length; a++)
            {
                dash[a] = '-';
                System.out.print(dash[a]);
            }
     
     
            while(hanged == false)
            {
     
            System.out.println();
     
     
     
            System.out.print("Enter guess: ");
            guess = scan.nextLine();
            check = guess.charAt(0);
     
     
            for(int b=0; b<dash.length; b++)
            {            
     
                if(check == word.charAt(b))                    
                    {                    
     
                        dash[b] = guess.charAt(0);
     
                        dash[word.indexOf(guess.charAt(0))] = check;
     
                        hanged = false;
                    }
     
                    else
                    {              
     
                        hanged = false;
                    }
     
     
                        System.out.print(dash[b]);   
            }
     
            test = new String(dash);
     
            if(word.equals(guess) || test.equals(word))
            {
                hanged = true;
            }
     
     
     
            }
     
        }
    }

  19. #19
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Java hangman help with comparing array to String

    What do these two lines of code do? Why are they both there?
                 dash[b] = guess.charAt(0);
     
                  dash[word.indexOf(guess.charAt(0))] = check;

    Why does the code set hanged = false inside the loop? If it had been set true, wouldn't that mean a match had been found?

    Why is guess.charAt(0) used in one place and check in another.
    Aren't they the same value?
    If you don't understand my answer, don't ignore it, ask a question.

  20. #20
    Member
    Join Date
    Jul 2013
    Location
    Baltimore, MD
    Posts
    59
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Java hangman help with comparing array to String

    Quote Originally Posted by Norm View Post
    What do these two lines of code do? Why are they both there?
                 dash[b] = guess.charAt(0);
     
                  dash[word.indexOf(guess.charAt(0))] = check;

    Why does the code set hanged = false inside the loop? If it had been set true, wouldn't that mean a match had been found?

    Why is guess.charAt(0) used in one place and check in another.
    Aren't they the same value?
    With out those two lines, my guess won't show up in the dash[]. It will display just -------
    I removed the second line, dash[word.indexOf(guess.charAt(0))] = check;, and it still works, so I guess I don't need that. I did a lot of troubleshooting, so I guess I forgot to clean up.
    I'm still new to boolean, so that's why I have the "false" inside loop. I did try it without the "false", and it works, so I'll be removing that also.

    --- Update ---

    New cleaned code

    I'm trying to add a counter to the program also.

    package test;
     
    import java.util.Scanner;
    import java.util.Random;
     
    public class Test {
     
        public static void main(String[] args) {
     
            Scanner scan = new Scanner(System.in);
            Random rand = new Random();
     
            int r;        
            String[] words = {"elephant"};
            char[] dash;
     
            String guess, word, test;
            char check;
            boolean hanged = false;
            int counter = 0;
     
            r = rand.nextInt(words.length);
            word = words[r];
            dash = new char[word.length()];
     
            for(int a=0; a<dash.length; a++)
            {
                dash[a] = '-';
                System.out.print(dash[a]);
            }
     
     
            while(hanged == false)
            {
     
            System.out.println();
     
     
     
            System.out.print("Enter guess: ");
            guess = scan.nextLine();
            check = guess.charAt(0);
     
     
            for(int b=0; b<dash.length; b++)
            {            
     
                if(check == word.charAt(b))                    
                    {                  
     
                        dash[b] = guess.charAt(0);
                    }
     
     
                        System.out.print(dash[b]);   
            }
     
            test = new String(dash);
     
            if(word.equals(guess) || test.equals(word))
            {
                hanged = true;
            }
     
     
     
            }
     
        }
    }


    --- Update ---

    do you have any tips on how to add the counter? I have to add the counter inside the loop right, since the if conditions are inside it?

    if the wrong choice is made, I want the counter to add by 1.
    if the correct choice is made, I want the counter to stay at the current number till another wrong choice is made
    when the counter is more than six, I want the game to end (player fails).

    this is what I have so far, but it's not working the way I want.

    package test;
     
    import java.util.Scanner;
    import java.util.Random;
     
    public class Test {
     
        public static void main(String[] args) {
     
            Scanner scan = new Scanner(System.in);
            Random rand = new Random();
     
            int r;        
            String[] words = {"elephant"};
            char[] dash;
     
            String guess, word, test;
            char check;
            boolean hanged = false;
            int counter = 0;
     
            r = rand.nextInt(words.length);
            word = words[r];
            dash = new char[word.length()];
     
            for(int a=0; a<dash.length; a++)
            {
                dash[a] = '-';
                System.out.print(dash[a]);
            }
     
     
            while(hanged == false)
            {
     
            System.out.println();
     
     
     
            System.out.print("Enter guess: ");
            guess = scan.nextLine();
            check = guess.charAt(0);
     
     
            for(int b=0; b<dash.length; b++)
            {            
     
                if(check == word.charAt(b))                    
                    {                  
     
                        dash[b] = guess.charAt(0);
                    }
     
                else
                {
                    counter++;
                }
     
     
                        System.out.print(dash[b]);   
            }
     
            System.out.println("Counter is " + counter);
     
            test = new String(dash);
     
            if(word.equals(guess) || test.equals(word))
            {
                hanged = true;
            }
     
     
     
            }
     
        }
    }

    Even if the correct letter is entered, it counts, in this example, the counter is supposed to be zero.

    run:
    --------
    Enter guess: e
    e-e-----Counter is 6
     
    Enter guess:

    Even if the wrong letter is entered, it counts, in this example, the counter is supposed to be 1

    run:
    --------
    Enter guess: w
    --------Counter is 8
     
    Enter guess:

  21. #21
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Java hangman help with comparing array to String

    What are you trying to count?
    The loop compares a single user input against all the letters in word.
    Do you want to count all the letters in the word that don't match the user's input?

    Should the count be incremented when a user's input does not match any letters in the word?
    A boolean variable could be used to detect if any match was found.
    If you don't understand my answer, don't ignore it, ask a question.

  22. #22
    Member
    Join Date
    Jul 2013
    Location
    Baltimore, MD
    Posts
    59
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Java hangman help with comparing array to String

    I'm trying to count the number of times the user guesses the wrong character

    Yes, the count should be incremented by 1 anytime the user guesses the wrong character

    How can I implement the boolean to do this?

    This should be my last part of the code, everything else seems to be done.

  23. #23
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Java hangman help with comparing array to String

    Look at and think about how you are using the hanged variable.
    The new variable will be used to detect when: "the user guesses the wrong character"
    or a better way to look at it: when the user guesses the correct character.
    If you don't understand my answer, don't ignore it, ask a question.

  24. The Following User Says Thank You to Norm For This Useful Post:

    tonynsx (October 2nd, 2013)

  25. #24
    Member
    Join Date
    Jul 2013
    Location
    Baltimore, MD
    Posts
    59
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Re: Java hangman help with comparing array to String

    Quote Originally Posted by Norm View Post
    Look at and think about how you are using the hanged variable.
    The new variable will be used to detect when: "the user guesses the wrong character"
    or a better way to look at it: when the user guesses the correct character.
    I'm sorry, but I don't know much about when and when not to use boolean. This is what I have so far

    package test;
     
    import java.util.Scanner;
    import java.util.Random;
     
    public class Test {
     
        public static void main(String[] args) {
     
            Scanner scan = new Scanner(System.in);
            Random rand = new Random();
     
            int r;        
            String[] words = {"elephant"};
            char[] dash;
     
            String guess, word, test;
            char check;
            boolean hanged = false;
     
            r = rand.nextInt(words.length);
            word = words[r];
            dash = new char[word.length()];
     
            for(int a=0; a<dash.length; a++)
            {
                dash[a] = '-';
                System.out.print(dash[a]);
            }        
     
            while(hanged == false)
            {
     
            System.out.println();
     
            System.out.print("Enter guess: ");
            guess = scan.nextLine();
            check = guess.charAt(0);
     
     
            for(int b=0; b<dash.length; b++)
            {            
     
                if(check == word.charAt(b))                    
                    {                  
     
                        dash[b] = guess.charAt(0);
     
                        hanged = false;
                    }
     
                else
                {
                        hanged = false;
                }
     
     
                        System.out.print(dash[b]);   
            }
     
            test = new String(dash);
     
            if(word.equals(guess) || test.equals(word))
                {
                    hanged = true;
                }
            }        
        }
    }

  26. #25
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Java hangman help with comparing array to String

    In the for loop, the posted code will always set hanged to false. There is no need to set hanged to false if that was its initial value because its value won't change unless the code sets it to true which is done when the game is over.
    If you don't understand my answer, don't ignore it, ask a question.

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. NullPointerException when comparing string in binary tree
    By tetkun in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 19th, 2013, 06:57 PM
  3. Reading a file and comparing them to an array to get the file type - java
    By tomb1992 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: March 4th, 2013, 06:13 PM
  4. error when comparing 2 string objects
    By amr in forum What's Wrong With My Code?
    Replies: 5
    Last Post: February 9th, 2011, 07:36 PM
  5. Hangman help. Comparing arrays and conditions.
    By javanewbie1 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: January 18th, 2011, 09:26 AM