Left Hand Side of an Assignment must be a Variable CharAt
Solution 1
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. That being said, you probably actually want
if (user.charAt(counter) == ' ')
which uses the comparison operator (==) and the space character (' '). ("" is an empty string)
Solution 2
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.
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.
Solution 3
You want to use the equality operator ==
, not the assignment operator =
.
Solution 4
"==" 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.
01jayss
Updated on September 23, 2020Comments
-
01jayss over 3 years
I currently have the following code for 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".
How would I solve this?
Thanks!
-
01jayss almost 12 yearsI changed it to "==", but now i get another error... the type of the left sub-expressoin "char" is not copmatible with the type of the right sub-expression "java.lang.String". How would I solve this?
-
templatetypedef almost 12 yearsActually... those "" should be ''. Otherwise +1.
-
Keith Flower almost 12 yearsMake your comparison with a character ie
' '
, not a string""
. -
templatetypedef almost 12 yearsYou can't have an empty character literal. It should probably be ' ', with a space.
-
Ravinder Reddy almost 12 years@templatetypedef Yes, mentioned in the answer