0
package com.chapter.BJ.UpperLower;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();

        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) >= 65 && str.charAt(i) <= 90) {
                str.charAt(i) += 32;
            } else if (str.charAt(i) <= 122 && str.charAt(i) >= 97) {
                str.charAt(i) -= 32;
            }
            System.out.print(str.charAt(i));
        }
    }

}

Hello everyone, I don't understand why I get an error on str.charAt(i) += 32; and str.charAt(i) -= 32;. Thank you for your help.

DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22
maricenaz
  • 1
  • 2
  • add the error stack trace in the question. – Jishnu Prathap Nov 06 '22 at 06:33
  • 2
    As specified in the Java Language Specification [15.26. Assignment Operators](https://docs.oracle.com/javase/specs/jls/se19/html/jls-15.html#jls-15.26-200): "**The result of the first operand of an assignment operator must be a variable, or a compile-time error occurs.**" - `...charAt(i)` is calling a method and it results in a value and not a variable (( also be aware that a string is immutable, it can not be changed - a new `String` must be created, or use a `StringBuilder` - I would also have a look at the documentation of `Character`, it may have some useful methods )) – user16320675 Nov 06 '22 at 06:56

2 Answers2

0

str.charAt(i) merely returns the character at that index. I assume you want to alter the character at that index, so what you are looking for is something like this.

Vinz
  • 483
  • 1
  • 10
0

The charAt() method simply returns the character at the specified index in a string. Its source code is below. It is an R-value and can be only used on the right side of assignment statements. But str.charAt(i) += 32; is equivalent to str.charAt(i) = str.charAt(i) + 32;, so you may get expected variable error.

public char charAt(int index) {
   if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
   }
   return value[index];
}

You can introduce a local variable to store stc.charAt(i) and update it as you need, like this.

for (int i = 0; i < str.length(); i++) {
    char c = str.charAt(i);
    if (str.charAt(i) >= 65 && str.charAt(i) <= 90) {
        c += 32;
    } else if (str.charAt(i) <= 122 && str.charAt(i) >= 97) {
        c -= 32;
    }
    System.out.print(c);
}

If you need to update str simultaneously, consider StringBuffer or StringBuilder since String is an immutable object.

kuriboh
  • 141
  • 5