Hey guys, I'm making a hangman project just for fun, and i was wondering if you could help me.

  • I have 5 classes
  • class 1- main (basically controlls everything except recognizing where the letters are located in the word and printing the hangman picture)
  • class 2- char_array (sees if the letter is in the word multiple times, and prints the letters the operator has figured out (ex: bumb-e) )

  • class 3 - graphics (just full of methods that print the hangman on the screen depending on how many letters you have gotten wrong)

  • class 4 - numbers (just has one method to decide what hangman picture to display)
  • class 5 - wordlist - a class that chooses a word from a list of many)

Where I am stuck is that the variables in the char_array class reset each time the init() or some_function() that gets called. Therefore, if i have a word with two of the same letter, the count gets messed up AND the the word with the dashes that the user sees (ex: G--gle) gets reset every time, so only the letter that you just entered will show up(ex: i enter g: G--g--, then i enter o: -oo---)

Here is the main class

import java.lang.reflect.Array;
import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;
import java.util.HashMap;
import java.io.*;


public class main{

    public static void main(String[] args){
        graphics graphics = new graphics();
        numbers numbers = new numbers();
        WordList words = new WordList();
        main main = new main();

        Scanner input = new Scanner(System.in);


        //String word[] = {"h", "i"};
        String word = new String(words.getword());
        String guessed_letters = new String("");

        int guesses_right = 0;
        int guesses_wrong = 0;

        int length = word.length();



        System.out.println("Hello, this is a hangman game. Good luck!");
        System.out.println(word);


        while(guesses_right != length && guesses_wrong != 6){
            System.out.println("Please enter a letter: ");
            String x = input.nextLine();

            if(isAlpha(x) && !(x.length() >1)){
                x = x.toLowerCase();

                if(word.contains(x) && !(guessed_letters.contains(x))){
                    System.out.println("------------------------------");
                    System.out.println("Good job, that is in the word");
                    char_array char_array = new char_array();
                    guessed_letters = guessed_letters + x;                  
                    char_array.init(word, x);
                    char_array.some_function();
                    System.out.println("DEBUG" + char_array.counter);
                    guesses_right = guesses_right + char_array.counter;
                    guesses_right++;
                    numbers.display_hangman(guesses_wrong);

                    System.out.println("Guessed_letters:" + guessed_letters);
                }
                else if (guessed_letters.contains(x)){
                    System.out.println("------------------------------");
                    System.out.println("I'm sorry, but you have already entered that number");
                }
                else if (!word.contains(x)){
                    //guessed_letters = guessed_letters + x;
                    if (guessed_letters.contains(x)){
                        System.out.println("------------------------------");
                        System.out.println("I'm sorry, but you have already entered that number.");
                    }
                    else{
                        System.out.println("------------------------------");
                        System.out.println("Sorry, that is not in the word");
                        guesses_wrong++;
                        numbers.display_hangman(guesses_wrong);
                    }
                    guessed_letters = guessed_letters + x;
                }           
            }else{
                System.out.println("I'm sorry, but it appears you have entered something that is invalid");
            }

        }
        if( guesses_wrong == 6){
            System.out.println("I'm sorry but it appears that you have lost. The word was " + word + ". Maybe try again?");
        }
        else{
            System.out.println("Congratulations!! You have won. The word was " + word + ". Maybe try again?");
        }

    }

    public static boolean isAlpha(String name){
        return name.matches("[a-zA-Z]+");
    }


}

-------------------------------------------------------------------------------
here is the char_array class

import java.lang.String;

public class char_array {

    public void init(String a, String b){
        word = a;
        x = b;

    }
    main main = new main();
    graphics graphics = new graphics();


    public String word;
    public String x;
    public int counter = 0;
    public void some_function() {
        //variable to increase in case of double letter
        char what_user_sees[] = new char[word.length()];
        char charArray[]=word.toCharArray();
            for(int i = 0; i <word.length(); i++){
                 what_user_sees[i] = '-';

            }


            for(int h=0;h<word.length();h++){  


                if (charArray[h] == x.charAt(0)){
                    what_user_sees[h] = x.charAt(0);
                    counter++;
                    //System.out.println(what_user_sees);
                }

            }

            System.out.println(what_user_sees); //print the thing with the hash marks

    }




}

These classes seem to be the ones that are causing the trouble. Could you guys modify the code for me so that the variables don't get reset every time?

Thanks in advance,
Brady

I would post the other classes, but they will just take up space, and i really don't think you will need them.

PS - if you guys could give me some better coding styles, that would be great. I'm just a beginner, So I'll take any advice that I can get.

Recommended Answers

All 9 Replies

welcome to daniweb :)

maybe you could post for the other classes as well , that way members could run it and check out the nuances themselves.. not only that , but it would be more fun too .. :) good to play hangman :)

however , at a first glance , i dont see the role of the counter variable inside the char_array() class , i dont see it being used for anything...
also ,

    public void init(String a, String b){
        word = a;
        x = b;

    }

this is supposed to (re)initialize it... with a new word. and it would have a cascading effect on some_function() as it works with the word initialized by init.
also , i have a feeling that char what_user_sees[] = new char[word.length()]; has a role to play in the re initialization , as what user sees shouldnt get a new char array everytime , rather it should be appended to what is there already...

Ok, since I'm a beginner I tried my best to interpret your comment. Ill post the classes that I fixed with the line in italics, and I'll post the rest of the classes that I didn't post in the last comment.

here is the char_array class that I fixed:

import java.lang.String;

public class char_array {

    public String word;
    public String x;
    public int counter = 0;//variable to increase in case of double letter. Added to counter in main function.

    public void init(String a, String b){
        word = a;
        x = b;

    }
    main main = new main();
    graphics graphics = new graphics();

    char what_user_sees[] = new char[word.length()];//I CHANGED THIS


    public void some_function() {

        //char what_user_sees[] = new char[word.length()];
        char charArray[]=word.toCharArray();
            for(int i = 0; i <word.length(); i++){
                 what_user_sees[i] = '-';

            }


            for(int h=0;h<word.length();h++){  


                if (charArray[h] == x.charAt(0)){
                    what_user_sees[h] = x.charAt(0);
                    counter++;
                    //System.out.println(what_user_sees);
                }

            }

            System.out.println(what_user_sees); //print the thing with the hash marks

    }




}

------------------------------------------------------------------------------------------------------
here is the graphics class:

public class graphics {
    public void no_body_part(){
        System.out.println( "*** You have 6 body parts left*** ");
        System.out.println( "|--|     ");
        System.out.println( "|     ");      
        System.out.println( "|     "); 
        System.out.println( "|     ");
        System.out.println( "|______");
        System.out.println( "|______|");
    }
    public void one_body_part(){
        System.out.println( "*** You have 5 body parts left*** ");
        System.out.println( "|--|     ");
        System.out.println( "|  o  ");      
        System.out.println( "|     "); 
        System.out.println( "|     ");
        System.out.println( "|______");
        System.out.println( "|______|");
    }

    public void two_body_part(){
        System.out.println( "*** You have 4 body parts left*** ");
        System.out.println( "|--|     ");
        System.out.println( "|  o  ");      
        System.out.println( "|  |  "); 
        System.out.println( "|     ");
        System.out.println( "|______");
        System.out.println( "|______|");
    }
    public void three_body_part(){
        System.out.println( "*** You have 3 body parts left*** ");
        System.out.println( "|--|     ");
        System.out.println( "|  o  ");      
        System.out.println( "| /" + "|" + "  " ); 
        System.out.println( "|     ");
        System.out.println( "|______");
        System.out.println( "|______|");
    }
    public void four_body_part(){
        System.out.println( "*** You have 2 body parts left*** ");
        System.out.println( "|--|     ");
        System.out.println( "|  o  ");      
        System.out.println( "| /" + "|" + "\\  " );
        System.out.println( "|     ");
        System.out.println( "|______");
        System.out.println( "|______|");
    }
    public void five_body_part(){
        System.out.println( "*** You have 1 body parts left*** ");
        System.out.println( "|--|     ");
        System.out.println( "|  o  ");      
        System.out.println( "| /" + "|" + "\\  " ); 
        System.out.println( "| /   ");
        System.out.println( "|______");
        System.out.println( "|______|");
    }
    public void six_body_part(){
        System.out.println( "*** You have 0 body parts left*** ");
        System.out.println( "|--|     ");
        System.out.println( "|  o  ");      
        System.out.println( "| /" + "|" + "\\  " ); 
        System.out.println( "| / \\ ");
        System.out.println( "|______");
        System.out.println( "|______|");
    }

}

-----------------------------------------------------------------------------------------------
here is the numbers class:

public class numbers {
    graphics graphics = new graphics();

    main main = new main();


    public void display_hangman(int x){
        if (x == 0){
            graphics.no_body_part();
        }
        else if (x == 1){
            graphics.one_body_part();
        }
        else if (x == 2){
            graphics.two_body_part();
        }
        else if (x == 3){
            graphics.three_body_part();
        }
        else if (x == 4){
            graphics.four_body_part();
        }
        else if (x == 5){
            graphics.five_body_part();
        }
        else if (x == 6){
            graphics.six_body_part();
        }
    }
}

------------------------------------------------------------------------------------------------
here is the wordList class: WARNING this is just copied from Yitzchak Weiser's hangman program.

import java.util.*;
public class WordList {
    //declare an array of all the words
    private String[] words = {"insert","moron","fool","bored","crazy","hello","nice","word","brother","senior","junior",
    "glasses","tiny","floor","code","internet","lake","sport","prince","aunt","seven","cartoon","trump","zebra","chalk",
    "random","person","movie","place","thing","rabbi","chest","hairy","clothes","close","open","closed","filled",
    "waste","find","easy","hard","pitch","base","come","twins","cracka","whatever","keyboard","actually","alabama","sixteen","computer","telephone","habitat","hangman","java" };



    public String getword() {
        //instantiate the random generator
        Random generator = new Random();
        //pick a random number 0-56
        int i = generator.nextInt(57);
        //returns the corresponding word in the array
        return words[i];
    }


}

main main = new main();
you dont have a Main() class , and main() , rather

public static void main(String[] args){}

in java serves a different purpose.. its the 1st method looked at by the jvm , without it , you cant compile your code.. so seems like a two - way error...
what did you intend on making this do? im sure we can fix that :)

edit : i just looked again , and you do have a main class! sorry about that... i overlooked the main class in the 1st post , but do you need all the different classes for this? it can be all done with one class. also , the graphics class you posted , just keep it as another method inside the char_array() class , and look up at the switch - case statements and how they work , they can really simplify your existing code.

another improvement , something that can make your code much simpler , is using ArrayLists . using that , you can check if the word contains the user input by simply using the contains() method of an arraylist. check these two out. its gonna be fun :)

I'm sorry. Like I said, I'm a beginner. I sort of understand what you are saying, but can you explain more?

And i found a bug that if you enter the first two letters right, it says you win automatically. Can you guys look at that too?

i hope you have taken a look at the links i asked you too , however , sometimes an example explains best. i modified your code a lot , and instead of all the classes , you have just one class now , the char_array{} class renamed to hangman ( just felt that to be more in place with things ) and the other classes you used to have , iv converted them into methods under the hangman class.

here is the code: (this is a basic stuff that will get you started with ideas)
i kept the chosen word as "pizza" as u'll see in the code , go ahead run it , put the words of pizza , and see what happens.

import java.util.*;

public class hangman {

    private static String[] words = {"insert","moron","fool","bored","crazy","hello","nice","word","brother","senior","junior",
                "glasses","tiny","floor","code","internet","lake","sport","prince","aunt","seven","cartoon","trump","zebra","chalk",
                "random","person","movie","place","thing","rabbi","chest","hairy","clothes","close","open","closed","filled",
                "waste","find","easy","hard","pitch","base","come","twins","cracka","whatever","keyboard","actually","alabama","sixteen","computer","telephone","habitat","hangman","java" };
    public String chosenWord;
    public String x;
    public int counter = 0;//variable to increase in case of double letter. Added to counter in main function.

    public hangman(){
        double r = 1 + Math.random()*words.length;
//      chosenWord = words[(int)r]; // eventually this should be used
        chosenWord="pizza"; // but its good to use what you know while building n testing your code.
//        x = b;

    }

    public void checkInput(Scanner is){
        boolean[] pos = new boolean[chosenWord.length()];
        int counter = 0;
        while(counter!=chosenWord.length()){
            System.out.println("\n enter letter: ");
            String ip = is.nextLine();
            for(int i = 0 ; i < pos.length ; i++){
                if(ip.charAt(0)==chosenWord.charAt(i)){
                    pos[i] = true;
                    counter++;
                } 
        }
            int i = 0;
            while(i<pos.length){
                if(pos[i]) System.out.print(" " + chosenWord.charAt(i));
                else System.out.print(" -");
                i++;
            }
        }


    }

    private void myGraphics(int bodyParts) {
        switch (bodyParts) {
        case 0:
            System.out.println( "*** You have 6 body parts left*** ");
            System.out.println( "|--|     ");
            System.out.println( "|     ");      
            System.out.println( "|     "); 
            System.out.println( "|     ");
            System.out.println( "|______");
            System.out.println( "|______|");
            break;

        case 1:
            System.out.println( "*** You have 5 body parts left*** ");
            System.out.println( "|--|     ");
            System.out.println( "|  o  ");      
            System.out.println( "|     "); 
            System.out.println( "|     ");
            System.out.println( "|______");
            System.out.println( "|______|");
            break;

        case 2:
            System.out.println( "*** You have 4 body parts left*** ");
            System.out.println( "|--|     ");
            System.out.println( "|  o  ");      
            System.out.println( "|  |  "); 
            System.out.println( "|     ");
            System.out.println( "|______");
            System.out.println( "|______|");
            break;

        case 3:
            System.out.println( "*** You have 3 body parts left*** ");
            System.out.println( "|--|     ");
            System.out.println( "|  o  ");      
            System.out.println( "| /" + "|" + "  " ); 
            System.out.println( "|     ");
            System.out.println( "|______");
            System.out.println( "|______|");
            break;

        case 4:
            System.out.println( "*** You have 2 body parts left*** ");
            System.out.println( "|--|     ");
            System.out.println( "|  o  ");      
            System.out.println( "| /" + "|" + "\\  " );
            System.out.println( "|     ");
            System.out.println( "|______");
            System.out.println( "|______|");
            break;

        case 5:
            System.out.println( "*** You have 1 body parts left*** ");
            System.out.println( "|--|     ");
            System.out.println( "|  o  ");      
            System.out.println( "| /" + "|" + "\\  " ); 
            System.out.println( "| /   ");
            System.out.println( "|______");
            System.out.println( "|______|");
            break;

        case 6:
            System.out.println( "*** You have 0 body parts left*** ");
            System.out.println( "|--|     ");
            System.out.println( "|  o  ");      
            System.out.println( "| /" + "|" + "\\  " ); 
            System.out.println( "| / \\ ");
            System.out.println( "|______");
            System.out.println( "|______|");
            break;

        default:
            break;
        }

    }
    public void display_hangman(int x){
        myGraphics(x);
    }
    public static void main(String[] args){
        Scanner is = new Scanner(System.in);
        hangman h = new hangman();
        h.checkInput(is);
    }
}

you should see that theres no graphics as of yet , and if you input a character that is already a part of the word more than once , that still increases the counter , and makes the game end before the word is complete. you should try to work around these problems. you have the foundation..

Thanks for all the help. I really, really do appreciate it. Here is the final class, and it all works. Go ahead and take whatever you want from it (if you want to) but just say you got it from me.

I got the word's from Yitzchak Weiser's, and somjit{} edited a lot of my code. Thanks for the help.

import java.util.*;
public class hangman {
    private static String[] words = {"insert","moron","fool","bored","crazy","hello","nice","word","brother","senior","junior",
                "glasses","tiny","floor","code","internet","lake","sport","prince","aunt","seven","cartoon","trump","zebra","chalk",
                "random","person","movie","place","thing","rabbi","chest","hairy","clothes","close","open","closed","filled",
                "waste","find","easy","hard","pitch","base","come","twins","cracka","whatever","keyboard","actually","alabama","sixteen","computer","telephone","habitat","hangman","java" };
    public String chosenWord;
    public String x;
    public String guessedLetters = "";
    public String wrongLetters = "";
    public int counter = 0;//variable to increase in case of double letter.
    public hangman(){
        double r = 1 + Math.random()*words.length;
        chosenWord = words[(int)r]; // eventually this should be used
        //chosenWord="pizza"; // but its good to use what you know while building n testing your code.
    }
    public void checkInput(Scanner is){
        boolean[] pos = new boolean[chosenWord.length()];
        int counter = 0;
        while(counter!=chosenWord.length() && !(wrongLetters.length() >5)){//i put 5 because it will already be in the loop when it reached 6
            System.out.println("----------------------------------"); //spacer
            System.out.println("Please enter a letter: ");
            String ip = is.nextLine();
            if(guessedLetters.contains(ip)){
                System.out.println("You have already guessed that letter... dumbass");
            }
            else if (ip.length() >1){
                System.out.println("What you have entered is more than one character long. Your and idiot");
            }
            else if (!(isAcceptable(ip))){
                System.out.println("Well, you have done something studpid enough that I don't know what you entered. Your name must be kaleb");
            }

            else{   
                guessedLetters = guessedLetters + ip;
                for(int i = 0 ; i < pos.length ; i++){
                    if(ip.charAt(0)==chosenWord.charAt(i)){
                        pos[i] = true;
                        counter++;
                    }
                }
                if(!(isIn(ip, pos))) {
                    wrongLetters = wrongLetters + ip; //if the guess is not in the word, then add it to wrongLetters
                }

                display_hangman(wrongLetters.length());
                System.out.println("Guessed Letters: " + guessedLetters);

                int i = 0;
                while(i<pos.length){
                    if(pos[i]) System.out.print(" " + chosenWord.charAt(i));
                    else System.out.print(" -");
                    i++;
                }
            }
            System.out.println(); // this is a spacer
        }
        if(counter == chosenWord.length()) {
            System.out.println("*********************************");
            System.out.println("*It looks like you won... try-hard ");
            System.out.println("*********************************");
        }
        else {
            System.out.println("*****************************************************************");
            System.out.println("* Well that sucks for you. YOU LOST..... LOSER The word was: " + chosenWord);
            System.out.println("*****************************************************************");
        }
    }
    private void myGraphics(int bodyParts) {
        switch (bodyParts) {
        case 0:
            System.out.println( "*** You have 6 body parts left*** ");
            System.out.println( "|--|     ");
            System.out.println( "|     ");      
            System.out.println( "|     "); 
            System.out.println( "|     ");
            System.out.println( "|______");
            System.out.println( "|______|");
            break;
        case 1:
            System.out.println( "*** You have 5 body parts left*** ");
            System.out.println( "|--|     ");
            System.out.println( "|  o  ");      
            System.out.println( "|     "); 
            System.out.println( "|     ");
            System.out.println( "|______");
            System.out.println( "|______|");
            break;
        case 2:
            System.out.println( "*** You have 4 body parts left*** ");
            System.out.println( "|--|     ");
            System.out.println( "|  o  ");      
            System.out.println( "|  |  "); 
            System.out.println( "|     ");
            System.out.println( "|______");
            System.out.println( "|______|");
            break;
        case 3:
            System.out.println( "*** You have 3 body parts left*** ");
            System.out.println( "|--|     ");
            System.out.println( "|  o  ");      
            System.out.println( "| /" + "|" + "  " ); 
            System.out.println( "|     ");
            System.out.println( "|______");
            System.out.println( "|______|");
            break;
        case 4:
            System.out.println( "*** You have 2 body parts left*** ");
            System.out.println( "|--|     ");
            System.out.println( "|  o  ");      
            System.out.println( "| /" + "|" + "\\  " );
            System.out.println( "|     ");
            System.out.println( "|______");
            System.out.println( "|______|");
            break;
        case 5:
            System.out.println( "*** You have 1 body parts left*** ");
            System.out.println( "|--|     ");
            System.out.println( "|  o  ");      
            System.out.println( "| /" + "|" + "\\  " ); 
            System.out.println( "| /   ");
            System.out.println( "|______");
            System.out.println( "|______|");
            break;
        case 6:
            System.out.println( "*** You have 0 body parts left*** ");
            System.out.println( "|--|     ");
            System.out.println( "|  o  ");      
            System.out.println( "| /" + "|" + "\\  " ); 
            System.out.println( "| / \\ ");
            System.out.println( "|______");
            System.out.println( "|______|");
            break;
        default:
            break;
        }
    }
    public void display_hangman(int x){
        myGraphics(x);
    }
    public boolean isIn(String ip, boolean[] pos){
        int checker = 0;
        for(int i = 0 ; i < pos.length ; i++){
            if(ip.charAt(0)==chosenWord.charAt(i)){
                pos[i] = true;
                checker++;
            }
        }
        if(checker != 0) return true;
        else return false;
    }
    public static boolean isAcceptable(String letter){
        return letter.matches("[a-zA-Z]+");
    }
    public static void main(String[] args){
        Scanner is = new Scanner(System.in);
        hangman h = new hangman();
        System.out.println("This is a hangman game made by Brady Brown. Have Fun!!");
        h.checkInput(is);
    }
}

if your problem's solved , please do mark the thread as solved too :)

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.