views:

120

answers:

4
private String kNow(String state, String guess) {
        for (int i = 0; i < word.length(); i++) {
            if (guess.equals(word.charAt(i))) {
                state.charAt(i) = word.charAt(i);
            }
        }
        return state;
    }

state.charAt(i) part points the problem in the title. How can I solve the problem, if my approach is not completely wrong.

+2  A: 

Strings are immutable in Java. This means that you cannot change a string object once you have created it. You can however create a new string and then reassign it to the variable.

state = state.substring(0, i) + word.charAt(i) + state.substring(i + 1);

However in this situation I think it would be better to use a mutable type for state such as a character array (char[]). This allows you to modify individual characters directly.

A second problem with your code is that guess should presumably be a char, not a string. Currently your if statement will always return false because an object of type string will never be equal to an object of type char.

Mark Byers
+2  A: 

Strings in Java are immutable: you can't change string after it's created. It might be better to use byte[] or char[] or collection for state.

Nikita Rybak
+6  A: 

The reason this doesn't work is because charAt(int x) is a method of the String class - namely it is a function, and you can't assign a function a value in Java.

If you want to loop through a string character by character, I might be tempted to do this:

Char[] GuessAsChar = guess.toCharArray();

Then operate on GuessAsChar instead. There are, depending on your needs, possibly better (as in neater) ways to approach searching for character equivalence in strings.

Ninefingers
+3  A: 

Not exactly sure what the intention is for guess.equals(word.charAt(i)) as that statement will always evaluate to false since a String never can equal a char, but you want to convert your String to a StringBuilder

private String kNow(String state, String guess) {
    final StringBuilder mutable = new StringBuilder(state);
    for (int i = 0; i < word.length(); i++) {
        if (guess.equals(word.charAt(i))) {
            mutable.setCharAt(i, word.charAt(i));
        }
    }
    return mutable.toString();
}
David Blevins
+1 For pointing out that the if statement always fails. i also added this to my anser (8 seconds before you :-P ) but it is such an important point that I think you should be upvoted too.
Mark Byers
This wouldn't compile. There is no `word` declared.
Willi
I imagine `word` is a field in the declaring class.
David Blevins