java - 赋值的左侧必须是变量 CharAt

标签 java string variable-assignment

我目前有以下 java 代码。

public class lesson8
{
    static Console c;           // The output console

    public static void main (String[] args)
    {
        c = new Console ();

        String user;
        int length, counter, spacecounter;
        spacecounter=0;
        c.print("Enter a string. ");
        user = c.readLine();

        length = (user.length()-1);

        for (counter=0;counter<length;counter++) 
        {
            if (user.charAt(counter) = "") 
            {
                spacecounter++;
            }
        }

        c.println("There are "+spacecounter+" spaces in your string.");
        c.println("There are "+counter+" characters in your string.");

        // Place your program here.  'c' is the output console
        // main method
    }
}

我在这部分遇到错误:

        if (user.charAt(counter) = "") 

错误是

The left-hand side of an assignment must be a variable.

我将其更改为“==”,但现在又出现另一个错误:

The type of the left sub-expression "char" is not compatible with the type of the right sub-expression "java.lang.String".

我该如何解决这个问题?

谢谢!

最佳答案

所以,为什么

if (user.charAt(counter) = "") 

给出的错误是“=”是java中的赋值运算符,因此左侧必须是一个变量。话虽这么说,你可能真的想要

if (user.charAt(counter) == ' ')

它使用比较运算符 (==) 和空格字符 (' ')。 (“”为空串)

关于java - 赋值的左侧必须是变量 CharAt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11354514/

相关文章:

java - Java 中的 XML 模板

python - 在 Python 中使用标题大写字符串的问题

string - Scala:分割字符串

python 字符串语法错误 += 运算符

java - 尝试使用资源为什么不能修改资源

Java 从 jar 文件加载图像

java - 没有到主机的路由 - connect(2) (Errno::EHOSTUNREACH)

java - 验证所有 JDBC 调用都发生在一个事务中

go - 在 Go 中,什么时候在多值赋值中复制值?

dart - 如何在Dart中的循环中更改对象值