0
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        char temp;
        char temp2;
        System.out.println("Enter Word");
        String x = in.next();
        System.out.println("Your Word has " + x.length()+ " Letters" + "\n");
        int[] array = new int[x.length()];
        for(int i = 0; i < array.length; i++){
            array[i] = x.charAt(i);
        }   
        temp = x.charAt(0);
        **x.charAt(0) = x.charAt(x.length);
        x.charAt(x.length()) = temp;**
        System.out.println(x);

    }

}

I wanted to switch the first Letter and the last letter of a word but I get this error The Left Hand Side Of An Assignment Must Be A Variable The error is in the X.charAt(0) = x.charAt(x.length) x.charAt(x.length()) = temp; Sorry if it's a dumb question I'm kind of new to programming.

lczapski
  • 4,026
  • 3
  • 16
  • 32
  • Not sure, but maybe the x.length() is returning a value that is one more than the position of the last char in String x. With java, usually the array elements are numbered 0..to n-1 where n is the length. Also the ** are a bit confusing. Those aren't actually in your code, are they? – Phil Freihofner Jun 18 '20 at 05:07
  • Ok, I'll check it out thanks! – ProgramShinobi Jun 18 '20 at 05:09
  • Possible duplicate of https://stackoverflow.com/questions/6952363/replace-a-character-at-a-specific-index-in-a-string – Sweeper Jun 18 '20 at 05:11
  • Also `String` objects are immutable – Scary Wombat Jun 18 '20 at 05:12

2 Answers2

0

x.charAt(0) or x.charAt(x.length()) is not a variable, it just return a value. For assigning a value left hand side must be a variable. String object is immutable. You can use StringBuilder or create char array then swap.

char arr[] = x.toCharArray();
char tmp = arr[x.length-1];
arr[x.length-1] = arr[0];
arr[0] = tmp;
Eklavya
  • 17,618
  • 4
  • 28
  • 57
0

As the other answer said, x.charAt(0) is not a variable.

So doing:

x.charAt(0) = x.charAt(x.length()-1);

would not work.

In Java Strings are not changeable. So if you really want to write an algorithm that needs to modify characters of a string in-place I'd suggest using StringBuilder:

StringBuilder sb = new StringBuilder(x);
sb.setCharAt(0, x.charAt(x.length()-1));

Note: x.charAt(x.length()) is beyond the end of the String since indices start with 0. So that's why I added a -1.

When you're done editing your StringBuilder you can convert it back to a String like this:

result = sb.toString();
AminM
  • 822
  • 4
  • 11