Unexpected Type errors

后端 未结 3 1453
臣服心动
臣服心动 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:31

    You can assign values to variables, not other values. Statements like 5 = 2 or 'a' = 'z' don't work in Java, and that's why you're getting an error. swapped.charAt(temp1) returns some char value you're trying to overwrite, it's not a reference to a particular position inside the String or a variable you can alter (also, mind that Java Strings are immutable so you can't really change them in any way after creation).

    Refer to http://docs.oracle.com/javase/7/docs/api/java/lang/String.html for information on using String, it should have a solution for what you're trying to do.

    Your code may even throw IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string. Check the length of each string.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-01-26 02:47

    The left side of your assignment cannot receive that value.

    0 讨论(0)
提交回复
热议问题