Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 223
01jayss Avatar asked Sep 01 '25 04:09

01jayss


1 Answers

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)

like image 142
Dennis Meng Avatar answered Sep 02 '25 18:09

Dennis Meng