简体   繁体   中英

Why am I getting error while using "str.charAt(i) = str.charAt(i+1)" in a loop

import java.io.*;
import java.util.Scanner;

class GFG {
    public static void main (String[] args) {
        String str;
        Scanner sc = new Scanner(System.in);
        str = sc.nextLine();

        for(int i=0; i<str.length();)
        {
            if(str.charAt(i)==str.charAt(i+1))
            {
                for(int j=i;j<str.length();j++)
                    str.charAt(j)=str.charAt(j+1); //Here the error occurs
            }
            else
            {
                i++;
            }
        }
        System.out.println(str);
    }
}

Exception:

error: unexpected type
                str.charAt(j)=str.charAt(j+1);
                          ^
  required: variable
  found:    value
1 error

str.charAt(j) returns a value. Eg The character "a".

This would be the equivalent of writing this:

"a" = str.charAt(j+1); // Doesn't work

Instead you want to assign replace a character of the String str .

Here is one method of doing this is to convert the string to a char array.

char[] strCharArray= str.toCharArray();
strCharArray[j] = str.charAt(j+1)

Alternatively you could use a StringBuilder.

StringBuilder str = new StringBuilder();
str.setCharAt(j, str.charAt(j+1));

you are using a getter to set a value.

use something like this :

str.setCharAt(j, str.charAt(j+1));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM