"The left-hand side of an assignment must be a variable" problem 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 points the problem in the title. How can I solve the problem, if my approach is not completely wrong.
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.
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();
}
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
.
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
.
精彩评论