Karan Singh
Karan Singh

Reputation: 11

Hangman program need advice

I'm new here and new to java programming and I need help with a hangman game I have to create for grade 11 com sci. I have to create dashes for a randomly generated word and replace the correct one with a letter the user inputs. I can replace the dash no problem its just that I am not able to keep it there as it is in a for loop. This is what I got:

'for(int e = 0; e < rndword.length; e++)
  {
    if(rndword[e] == guess.charAt(0))
    {
      System.out.print(guess);
    }
    else if(rndword[e] == ' ')
    {
     System.out.print(" ");
    }
    else
    {
     System.out.print("-");
    }


  }`

A sample output would be:

word: canon

Enter a Letter: "o"

---o-

Enter a Letter: "c"

c----

The previous inputted letter would not reappear.

Thanks in advance!

(P.S. I am fairly new to java so all I know are arrays, switch, for/while loops,and do while loops)

Upvotes: 0

Views: 62

Answers (2)

2ARSJcdocuyVu7LfjUnB
2ARSJcdocuyVu7LfjUnB

Reputation: 435

quick implementation of my comment:

String randomWord;
char[] display;
char guess;

void nextGame(){
    randomWord = <whatever you do here>;
    word = new char[randomWord.length()];
}

for(int e = 0; e < randomWord.length; e++) {
    if(randomWord[e] == guess)
       display[e] = guess;
}

void checkWon() {
    for(char c : display) 
       if(c == '-'){
          System.out.print(display); return;
       }

    System.out.println("Won message.");
}

Upvotes: 0

nhouser9
nhouser9

Reputation: 6780

A better way to do this would be to store two arrays, one for what should be shown to the user and one for the real word.

Then when the user gets a letter right, you can modify the array shown to the user.

Something like:

char[] rndword; //put the word they are trying to guess here
char[] display; //show this one to the user (start by populating it with dashes and / or spaces)

for(int e = 0; e < rndword.length; e++) {
    if(rndword[e] == guess.charAt(0))
    {
        display[e] = guess.charAt(0);
    }
    System.out.print(display[e]);
}
System.out.println();

So display would start out like "---- -- ----", but if the user guesses 'A' and it has an 'A', it would be changed to "--A- -- -A-A" and then printed out.

Upvotes: 1

Related Questions