“赋值的左边必须是一个变量"charAt 的问题 [英] "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) 部分指出了标题中的问题.如果我的方法不是完全错误,我该如何解决问题.
state.charAt(i) part points the problem in the title. How can I solve the problem, if my approach is not completely wrong.
推荐答案
这个不行的原因是因为charAt(int x)
是String
class - 即它是一个函数,您不能在 Java 中为函数赋值.
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();
然后对 GuessAsChar 进行操作.根据您的需要,有可能更好(如更简洁)的方法来搜索字符串中的字符等效性.
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.
这篇关于“赋值的左边必须是一个变量"charAt 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!