赋值语句的左侧必须是一个变量,CharAt是什么意思?

3

我目前有以下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) = "") 

错误是:

赋值语句的左侧必须是一个变量。

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

左子表达式“char”的类型与右子表达式“java.lang.String”的类型不兼容。

我该如何解决这个问题?

谢谢!

5个回答

9
所以,之所以
if (user.charAt(counter) = "") 

出现这个错误是因为“=”在Java中是一个赋值运算符,因此左侧必须是一个变量。话虽如此,你可能实际上想要使用

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

该操作使用比较运算符(==)和空格字符(' ')。(""表示空字符串)


2

您正在使用赋值运算符覆盖比较运算符。

请更改为

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

to

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

更新:
你在比较时也出现了错误。如果要比较 char,你应该使用单引号('),否则代码将无法编译。

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

但是这段代码不会被编译,因为零长度的字符未定义。
你应该比较一个有效的字符,例如空格 ' '。

1
实际上...那些""应该改成''。否则+1。 - templatetypedef
你不能有一个空的字符字面量。它应该是一个空格 ' '。 - templatetypedef
@templatetypedef 是的,在答案中提到了。 - Ravinder Reddy

1
您应该使用相等运算符 ==,而不是赋值运算符 =

我将它改为“==”,但现在出现了另一个错误...左子表达式的类型是“char”,与右子表达式“java.lang.String”的类型不兼容。我该如何解决? - 01jayss
请使用字符 ' ' 而不是字符串 "" 进行比较。 - Keith Flower

1
"

==

会确保右边的值与左边的变量相同。

"=

是一个赋值运算符,用于给变量赋值,而不是比较它。

"

0

我的代码出现了同样的错误。加上括号解决了这个问题。

从以下内容进行了更改:

if(isNotNullorEmpty(operator)) 
                ArrayList<String> result =  getOperatorAndTypeforName(name );

if(isNotNullorEmpty(operator)){ 
                ArrayList<String> result = getOperatorAndTypeforName(name );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接