简体   繁体   English

“赋值的左侧必须是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) part points the problem in the title. state.charAt(i)部分指出标题中的问题。 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. 这不起作用的原因是因为charAt(int x)String类的一个方法 - 即它是一个函数,并且您不能在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. 然后在GuessAsChar上操作。 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 不完全确定guess.equals(word.charAt(i))的意图是什么,因为该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();
}

Strings are immutable in Java. 字符串在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[] ). 但是在这种情况下,我认为最好使用一个可变类型的state ,如字符数组( 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. 你的代码的第二个问题是guess应该是char,而不是字符串。 Currently your if statement will always return false because an object of type string will never be equal to an object of type char . 目前, if语句将始终返回false,因为string类型的对象永远不会等于char类型的对象。

Strings in Java are immutable: you can't change string after it's created. Java中的字符串是不可变的:在创建字符串后不能更改字符串。 It might be better to use byte[] or char[] or collection for state . 使用byte[]char[]或集合进行state可能更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM