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);
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.
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);
The left side of your assignment cannot receive that value.