Home > Blockchain >  about multiple markers error on str.charAt(i) with operators
about multiple markers error on str.charAt(i) with operators

Time:11-06

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.

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • java
  • Related