这是我的密码:
class Backwards {
String str;
Backwards(String s) {
str = s;
}
void backward(int idx) {
if(idx != str.length()-1) {
System.out.println(idx);
backward(++idx);
}
System.out.print(str.charAt(idx));
}
}
class StrBackDemo {
public static void main(String args[]) {
Backwards s = new Backwards("This is a test");
s.backward(0);
}
}
当我用表达式idx +1
调用函数本身时,它工作得很好,但是对于++idx
,它会打印两次第一个字符,并且根本不打印最后一个字符。
With <+idx> output: ttset a si sih
With <idx +1> output: tset a si sihT
发布于 2017-03-30 20:31:06
++i将增加i的值,然后返回递增的值。
i = 1;
j = ++i;
(i is 2, j is 2)
i++将增加i的值,但返回在增量之前持有的原始值。
i = 1;
j = i++;
(i is 2, j is 1)
因此,在您的代码局外人中,idx =0;
System.out.println(idx); //idx = 0;
backward(++idx); //its changed idx = 1 and passed 1 to this function
System.out.print(str.charAt(idx));//After all recursion call here idx =1 not idx =0;
因此,你得到了错误的结果。
但在idx+1的情况下;
System.out.println(idx); //idx = 0;
backward(idx+1); //its changed idx = 0 but passed 1 to this function
System.out.print(str.charAt(idx));//After all recursion call here idx =0
发布于 2017-03-30 20:36:17
这是在递归调用backward(++idx)
上传递增量值和增量值本身的原因。运算符++
将idx
的值设置为idx + 1
最后一次调用结束时,方法获取索引13并打印它的字符,而前面的调用也有索引13。同时,方法的第一次调用有索引1。
要修复您的代码,请使用:
void backward(int idx) {
if(idx != str.length()-1) {
System.out.println(idx);
backward(idx + 1);
}
System.out.print(str.charAt(idx));
}
使用idx + 1
时,idx
的值将保持不变,即调用它。
https://stackoverflow.com/questions/43127487
复制相似问题