[英]Left Hand Side of an Assignment must be a Variable CharAt
I currently have the following code for java.我目前有以下 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
}
}
I am getting an error on this part:我在这部分遇到错误:
if (user.charAt(counter) = "")
The error is错误是
The left-hand side of an assignment must be a variable.赋值的左边必须是一个变量。
I changed it to "==", but now I get another error:我将其更改为“==”,但现在又出现另一个错误:
The type of the left sub-expression "char" is not compatible with the type of the right sub-expression "java.lang.String".左子表达式“char”的类型与右子表达式“java.lang.String”的类型不兼容。
How would I solve this?我将如何解决这个问题?
Thanks!谢谢!
So, the reason why所以,之所以
if (user.charAt(counter) = "")
gives that error is that "=" is an assignment operator in java, and so the left-hand side must be a variable.给出的错误是“=”是java中的赋值运算符,因此左侧必须是变量。 That being said, you probably actually want话虽这么说,你可能真的想要
if (user.charAt(counter) == ' ')
which uses the comparison operator (==) and the space character (' ').它使用比较运算符 (==) 和空格字符 (' ')。 ("" is an empty string) (“”是一个空字符串)
You are using an asignment over a comparison operator.您正在对比较运算符使用赋值。
Change改变
if (user.charAt(counter) = "")
to到
if (user.charAt(counter) == "")
Update:更新:
You also have an error at comparison again.您再次比较时也有错误。 You should also use single quotes ( ' )
to compare a char
, otherwise it won't get compiled.您还应该使用single quotes ( ' )
来比较char
,否则它不会被编译。
if (user.charAt(counter) == '')
But this too will not get compiled as a zero length char is not defined.但这也不会被编译,因为未定义零长度字符。
You should be comparing a valid character, say ' ' for space .您应该比较一个有效字符,比如 ' ' 代表空格。
You want to use the equality operator ==
, not the assignment operator =
.您要使用相等运算符==
,而不是赋值运算符=
。
"==" is going to make sure that the value to the right is the same as the variable to the left. “==”将确保右边的值与左边的变量相同。
"=" is an assignment operator and is used to give value TO the variable, rather than compare it. “=”是一个赋值运算符,用于给变量赋值,而不是比较它。
I got same error in my code.我的代码中出现了同样的错误。 Adding parenthesis solved this error添加括号解决了这个错误
Changed from改自
if(isNotNullorEmpty(operator))
ArrayList<String> result = getOperatorAndTypeforName(name );
to到
if(isNotNullorEmpty(operator)){
ArrayList<String> result = getOperatorAndTypeforName(name );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.