我正在研究一个我设计一种递归地计算字符串中x出现的方法的问题。从代码下面的输出中可以看到,当i == 6时,也包含递归调用的if条件不再执行。但是,为什么要多次打印“ countKeep is 4”?
此外,当我取消注释时,行数= 0;我只收到一次“ countKeep为4”,而以下几行打印“ countKeep为0”并返回0。
据我了解,变量countKeep应该设置为变量count。然后,将变量count和i设置为以下字符串的0。然后返回countKeep并给出该字符串中x的出现。
我对这个初学者的问题缺少什么?
我通过以下方式调用该方法:
System.out.println(p.countX("xxhixx"));
int count;
int countKeep;
int i;
public int countX(String str) {
if (i < str.length()) {
System.out.println("i in outer if is " +i);
if (str.charAt(i) == 'x') {
count++;
System.out.println("count in inner if is " + count);
}
i++;
System.out.println("i is " +i);
countX(str);
}
countKeep = count;
System.out.println("countKeep is " + countKeep);
// count = 0;
// i = 0;
return countKeep;
}
输出:
i in outer if is 0
count in inner if is 1
i is 1
i in outer if is 1
count in inner if is 2
i is 2
i in outer if is 2
i is 3
i in outer if is 3
i is 4
i in outer if is 4
count in inner if is 3
i is 5
i in outer if is 5
count in inner if is 4
i is 6
countKeep is 4
countKeep is 4
countKeep is 4
countKeep is 4
countKeep is 4
countKeep is 4
countKeep is 4
4
最佳答案
在达到countKeep的设置并进行打印之前,请再次调用countX()方法。因此,只有在完成对countX()的所有调用后,它才会到达此代码(if语句之后的代码)。因此,它也被称为6次。
以下代码将更好地显示实际情况:
System.out.println(p.countX("xxhixx"));
int count;
int countKeep;
int i;
public int countX(String str) {
if (i < str.length()) {
System.out.println("i in outer if is " +i);
if (str.charAt(i) == 'x') {
count++;
System.out.println("count in inner if is " + count);
}
i++;
System.out.println("i is " +i);
countKeep = count;
System.out.println("countKeep is " + countKeep);
countX(str);
}
System.out.println("Finished the countX() method");
return countKeep;
}