"The left side of the job must be variable" with charAt

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 indicates a problem in the name. How can I solve the problem if my approach is not quite right.

+3
source share
4 answers

The reason this does not work is because it charAt(int x)is a class method String, namely a function, and you cannot assign a function a value in Java.

If you want to scroll a string character by character, I may be tempted to do this:

Char[] GuessAsChar = guess.toCharArray();

Then use GuessAsChar. Depending on your needs, it might be better (as in neat) ways to approach the search for equivalence of characters in strings.

+9
source

, guess.equals(word.charAt(i)), false, String char, String 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();
}
+4

immutable Java. , . , .

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

, state, (char[]). .

, guess char, . if false, string char.

+2
source

Strings in Java are immutable: you cannot change a string after it is created. It might be better to use byte[]either char[]or or a collection for state.

+2
source

Source: https://habr.com/ru/post/1763169/


All Articles