01jayss
01jayss

Reputation: 1449

Left Hand Side of an Assignment must be a Variable CharAt

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!

Upvotes: 4

Views: 110199

Answers (5)

upog
upog

Reputation: 5531

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 );
}

Upvotes: 0

Ravinder Reddy
Ravinder Reddy

Reputation: 24002

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.

Upvotes: 2

Dennis Meng
Dennis Meng

Reputation: 5187

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)

Upvotes: 10

BlackHatSamurai
BlackHatSamurai

Reputation: 23493

"==" 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.

Upvotes: 1

Keith Flower
Keith Flower

Reputation: 4152

You want to use the equality operator ==, not the assignment operator = .

Upvotes: 1

Related Questions