我在此代码上不断收到意外的类型错误,但我不太确定在哪里。您能找出我要去哪里了吗?
public String rev(String word, int start, int end){
String input = word;
while(start < end){
char hold = input.charAt(start);
input.charAt(start) = input.charAt(end);
input.charAt(end) = hold;
start++;
end--;
}
return input;
}
答案 0 :(得分:4)
您无法分配给input.charAt(start)
或input.charAt(end)
。将String
转换为char[]
,进行相应的工作,然后最后将其转换回去。
char[] chars = input.toCharArray();
// your loop here . . .
return new String(chars);
不能分配给charAt
方法的返回值的原因是它不是所谓的左值。尽管“ lvalues”和“ rvalues”在Java规范中称为“变量”和“ values”,但它与rvalue一起可以追溯到C编程语言。这个想法是只有某些东西可以出现在赋值运算符的左侧(LHS)。在Java中,左值可以是局部变量,字段,静态(类)变量,数组元素-必须是可以为其分配值的东西。 charAt
方法返回实际值,而不是对支持字符串的数组元素的引用,因此它是一个右值,并且不能出现在赋值的LHS中。
此外,Java中的字符串是不可变的,因此即使语法没有错误,您仍然无法直接修改字符串。
答案 1 :(得分:0)
您不能在=
的左侧放置函数调用。请注意,input.charAt(start)
是一个函数调用,您将在字符串charAt
上调用函数input
。
执行以下操作:
public class Main {
public static void main(String[] args) {
// Test
System.out.println(rev("Hello", 0, 4));
}
public static String rev(String word, int start, int end) {
if (word == null || word.length() == 1) {
return word;
}
if (start < 0) {
start = 0;
}
if (end >= word.length()) {
end = word.length() - 1;
}
char[] input = word.toCharArray();
char hold;
while (start < end) {
hold = input[start];
input[start] = input[end];
input[end] = hold;
start++;
end--;
}
return new String(input);
}
}
输出:
olleH