-1

I'm using the following code to add a guessed consonant to a string of stars if the guessed consonant is part of the original word. Initially I was keeping wordWithGuess between calls to getCurrentResult. But the result of this was that the new content was added to the end, and wordWithGuess kept getting longer (instead of just replacing the most recently guessed letter).

When running the code below, the output is

After guessing r: *****r******
After guessing s: ************
After guessing t: **tt********
After guessing l: ********ll**
After guessing n: ***********n

My goal is for it to be:

After guessing r: *****r******
After guessing s: *****r******
After guessing t: **tt*r******
After guessing l: **tt*r**ll**
After guessing n: **tt*r**ll*n

Sample code follows:

public class Sample {
    String targetWord;
    String wordWithGuess = "";

    public Sample(String targetWord) {
        this.targetWord = targetWord;
    }

    public void guess(String consonant) {
        wordWithGuess = "";

        for (int i = 0; i < targetWord.length(); i++) {
            if (targetWord.substring(i, i + 1).equals(" ")) {
                wordWithGuess += " ";
            } else if (targetWord.substring(i, i + 1).equals(consonant)) {
                wordWithGuess += consonant;
            } else {
                wordWithGuess += "*";
            }
        }
    }

    public String getCurrentResult() {
        return wordWithGuess;
    }

    public static void main(String args[]) {
        String targetWord = "bitterbollen";

        Sample sample = new Sample(targetWord);

        String[] guesses = { "r", "s", "t", "l", "n" };

        for (String guess : guesses) {
            sample.guess(guess);
            System.out.println("After guessing " + guess + ": "
                    + sample.getCurrentResult());
        }
    }
}
GargantuChet
  • 5,691
  • 1
  • 30
  • 41
Jente
  • 63
  • 1
  • 8
  • Why did I get downvoted, did I do something wrong? – Jente Jan 07 '13 at 01:29
  • For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Jan 07 '13 at 01:40
  • Someone linked that to me before but I don't quite understand that. Could you perhaps link me an example of that? Thanks – Jente Jan 07 '13 at 01:46
  • See e.g. [1](http://stackoverflow.com/questions/7143287/how-to-best-position-swing-guis/7143398#7143398), [2](http://stackoverflow.com/questions/7861724/is-there-some-word-wrap-property-of-jlabel-exist/7861833#7861833), [3](http://stackoverflow.com/questions/6295084/cut-out-image-in-shape-of-text/6296381#6296381).. – Andrew Thompson Jan 07 '13 at 01:55
  • 2
    I'm unclear about how this code sample could even the example output you provided. `wordWithGuess += consonant; wordWithGuess += 1;` should result in something like `***o1****`. And there's a typo ("woord") in your `if` statement. To Andrew Thompson's point, it would be much easier to understand the issue you face if a short, self-contained example program were given (rather than something that "looks like" the actual code). – GargantuChet Jan 07 '13 at 02:00
  • @GargantuChet I'm sorry, the names are originally in dutch so I need to translate them. as for the +1 it's a piece of code i forgot to remove. I updated the original post with what it looks like right now. – Jente Jan 07 '13 at 02:13
  • *"I updated the original post with what it looks like right now."* Update the original post with an **SSCCE.** – Andrew Thompson Jan 07 '13 at 02:37
  • 3
    @Jente, I've edited your post pretty heavily. I tried to keep the spirit of your question, and use your provided code to build a small, self-contained example program as the basis for discussion. Hopefully it gives you a better idea of what Andrew is talking about. If I've changed your question too heavily, feel free to roll it back (or comment here, and I'll do it personally). – GargantuChet Jan 07 '13 at 03:01
  • @GargantuChet I was actually trying it myself but when I pressed save it told me you had already done this, thank you for that. It's much better than what I had and I think I understand how to properly ask a question now. – Jente Jan 07 '13 at 03:09
  • @Jente, great! I've updated my answer below to show a few approaches. Feel free to comment on the answer if there's anything you'd like me to clarify. – GargantuChet Jan 07 '13 at 03:56

4 Answers4

1

The problem is that you need to keep some information between calls to guess(). This means either storing all values of consonant, or finding a way to merge the old value of wordWithGuess with the new consonant.

The first option means something like

import java.util.Set;
import java.util.HashSet;

class Sample {

    // ...

    Set<String> guesses = new HashSet<String>();

    public void guess(String consonant) {
        guesses.add(consonant);

        wordWithGuess = "";

        for (int i = 0; i < targetWord.length(); i++) {
            String cursor = targetWord.substring(i, i + 1);

            if (cursor.equals(" ")) {
                wordWithGuess += " ";
            } else if (guesses.contains(cursor)) {
                wordWithGuess += cursor;
            } else {
                wordWithGuess += "*";
            }
        }
    }

    // ...

}

This stores the old guesses as a Set. Instead of just checking for the last guess, guess() now includes any letter that has been guessed.

In fact you could even add a constructor to initialize the set with any characters that you want to include by default. This will let you eliminate the check for a space, as it'll be in the initial set of guesses:

import java.util.Set;
import java.util.HashSet;

class Sample {

    // ...

    Set<String> guesses;

    public Sample() {
        this.guesses = new HashSet<String>();
        guesses.add(" ");
    }

    public void guess(String consonant) {
        guesses.add(consonant);

        wordWithGuess = "";

        for (int i = 0; i < targetWord.length(); i++) {
            String cursor = targetWord.substring(i, i + 1);

            if (guesses.contains(cursor)) {
                wordWithGuess += cursor;
            } else {
                wordWithGuess += "*";
            }
        }
    }

    // ...

}

The other option would be to update wordWithGuess to include the new guess. In C it's easy to do this, because strings can be modified just like character arrays (for example, wordWithGuess[i] = consonant. Java guards its strings more closely, but there's no reason why one can't use an array of char to the same effect.

public class Sample {
    String targetWord;
    char[] currentResult;

    public Sample(String targetWord) {
        this.targetWord = targetWord;
        currentResult = new char[targetWord.length()];
        for (int i = 0; i < targetWord.length(); i++) {
            if(targetWord.charAt(i) == ' ') {
                currentResult[i] = ' ';
            } else {
                currentResult[i] = '*';
            }
        }
    }

    public void guess(String consonant) {
        for (int i = 0; i < targetWord.length(); i++) {
            String cursor = targetWord.substring(i, i + 1);

            if (cursor.equals(consonant)) {
                currentResult[i] = consonant.charAt(0);
            }
        }
    }

    public String getCurrentResult() {
        return new String(currentResult);
    }

    // ...

}
GargantuChet
  • 5,691
  • 1
  • 30
  • 41
  • So I changed that, now it doesn't add to it anymore which is good though now it forgets the first consonant guess when I run through it a second time. Thanks – Jente Jan 07 '13 at 01:31
  • I was looking into something like your 3rd option but couldn't quite get it to work. Thanks! – Jente Jan 07 '13 at 04:00
1

you should store all consonants guessed, and change word.substring(i, i + 1).equals (consonant)

to something like

word.substring(i, i + 1) exists in the consonant guessed. (it is pusedo-code of course)

Some more hints: have a look in Set (or more precisely, HashSet), or String's contains() or indexOf() method.


Some extra opinions to you:

you are calling word.substring(i, i + 1) without storing the returned string, that's a meaningless call.

Instead calling word.substring(i, i + 1) that many times, you can call it once and use the returned string for multiple comparison.

And, as you are comparing one char each time, you should use char to store the character, and using charAt() to get the character at certain position.

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
0

You'll want to store the result of the previous iteration. Have the code oldWordWithGuess = wordWithGuess at the end of the for loop.

Then, in your loop you'll want the following code:

...
if(oldWordWithGuess[i] != `*`) {
    wordWithGuess += oldWordWithGuess[i];
} else if (word.substring(i, i + 1).equals (" ")) {
...

That way it will put any previous guesses in.

Jeff
  • 12,555
  • 5
  • 33
  • 60
0

I've actually found a different solution where I use a char Array and store every letter in a different element of that array. Am I actually allowed to do this? Does this not require too much resources for what it does?

Jente
  • 63
  • 1
  • 8