-1

Can someone help me understand why I'm getting an "Unexpected Type Error"?

if(s.charAt(i-1) == ' '){
    String sub = s.substring(i, s.indexOf(' ')+1);
    for(int j = 0; j < sub.length()/2; j++){
        char temp;
        temp = sub.charAt(j);
        sub.charAt(j) = sub.charAt(sub.length()-1-j);
        sub.charAt(sub.length()-1-j) = temp;
        sub = sub+" ";
        complete = complete+sub;
    }
}

I'm getting the error on lines 6 and 7. I can't figure out why and I'd appreciate the help!

user3412722
  • 61
  • 1
  • 4
  • 11

2 Answers2

5

charAt() returns the character. It is not a left side operand aka you cannot assign a value to it. Strings are immutable, which means you cannot change them (this seems to be your intention). Instead: create a new String and add to that.

If this confused you, I try to elaborate a little: the assignment operator takes whatever is on the right and tries to shove it into whatever is on the left of it.

The problem here is that some things do not like it when you try to shove other things into them. You cannot put everything on the left that you want. Well, you can try:

"everything" = 5;

but this does not work, neither does this:

"everything" = 42;

Set aside what that last snippet failing implies to the universe and everything, your problem at hand is that charAt() is also one of those things that do not like it on the left side of the assignment operator. I'm afraid there's no way to turn charAt() into one of those things that like it on the left side. A week after stranding on a deserted island without any plants but only solar powered refrigerators filled with steaks, this probably works:

vegetarian = meat;

Even though the vegetarian doesn't like it there, he'd accept his situation being on the left side of the = operator. He eats some steaks. This does not hold true for what you are trying, though. There's no such deserted island for charAt().

null
  • 5,207
  • 1
  • 19
  • 35
1

In these lines you're trying to set the value of functions' return. This is illegal

 sub.charAt(j) = sub.charAt(sub.length()-1-j);
 sub.charAt(sub.length()-1-j) = temp;

as far as I see you're trying to change the characters of a String, but Strings are imutable objects. So you'll need to use a StringBuffer to set the values.