Unexpected Type errors

后端 未结 3 1452
臣服心动
臣服心动 2021-01-26 01:52

I\'m getting two small unexpected type errors which I\'m having trouble trying to solve.

The errors occur at:

swapped.charAt(temp1) = str.charAt(temp2);
         


        
3条回答
  •  伪装坚强ぢ
    2021-01-26 02:38

    Description of String#charAt(int):

    Returns the char value at the specified index

    It returns the value of the character; assigning values to that returned value in the following lines is the problem:

    swapped.charAt(temp1) = str.charAt(temp2);
    swapped.charAt(temp2) = temp1;
    

    Also, String#charAt(int) expects an index of a character within the String, not the character itself (i.e. chatAt(temp1) is incorrect), so your method will not work as expected even if you fix the former problem.

    Try the following:

    String swapped;
    if(swap1 > swap2) {
        swap1+=swap2;
        swap2=swap1-swap2;
        swap1-=swap2;
    }
    if(swap1!=swap2)
        swapped = str.substring(0,swap1) + str.charAt(swap2) + str.substring(swap1, swap2) + str.charAt(swap1) + str.substring(swap2);
    

提交回复
热议问题