我目前有以下 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/