Equinoxinator Equinoxinator - 1 year ago 92
Java Question

Basic Hangman game in Java (mostly concerns string manipulation)

I am taking an intro class to java and we have a project that deals with a hangman game. I have most of the code worked out but there is a bug that I can't seem to resolve.

First, the program prompts the user for a letter and one space where they think the letter goes, then the program displays a word in a series of hyphens and, if the user makes a correct guess, the letter in the corresponding hyphen is replaced with said letter.

For testing purposes , the word has been defaulted to "narrow."

So if I were to guess the letter "r" and for space, I were to guess index 2, the program would give me:

Guess a letter: r

Guess a space: 2

Guess: --r---

The problem I am having is that when I guess the index 3 for space and try to guess the next r, the program just gives me the same output as before.

We are not allowed to use arrays or string builder because we have not talked about them yet.

Here are my variables:

// default word for testing
String blank = "narrow";

// variables to manipulate the string
String start = "";
String end = "";
String word = "";

// variables for input and output
// input is used for the user's letter guess
String input;
// space is used for the user's index guess
String space = "";
// guess is used at the end to display the word to the user and set equal to word after
// it has been manipulated
String guess = "";

Here is the code where the string is being manipulated.

for (int i = 0; i < blank.length(); i++) {
if (i == blank.indexOf(input)) {
start = guess.substring(0, i);
end = guess.substring(i + 1);
word = start.concat(input).concat(end);

I think it has to do with the if statement, but I have tried some other things and they have not worked. Any help would be appreciated.

Thank you.

Answer Source

The problem with your code is that everytime the blank.indexOf(input) returns 2 everytime (indexOf returns the first occurance of 'r' which is 2)

You can change the condition to check if the character at the space that the user guessed is the contains the letter that the user guessed. You can do this as follows:

  1. Maintain the pattern to be printed. Make a variable for this.
  2. update the pattern everytime the user guesses correctly.

Note: In the below code guess is the variable I am talking about which is initially set to "------" for the word "narrow"

    // check if the space has the letter you guessed
    if (blank.charAt(space) == input.charAt(0)) {
         // if it has just update the pattern string to also contain the new letter
         guess = guess.substring(0, space) + input + guess.substring (space + 1)

You can just print or return (if it is a method) the pattern string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download