我正在研究一个问题,我设计了一种方法,用递归方法计算字符串中x的出现次数。正如您在i == 6时从代码下方的输出中看到的那样,if条件也包含递归调用,不再进一步。但是为什么" countKeep是4"多次打印? 此外,当我取消注释行数= 0时;我只收到" countKeep是4"一次,而以下行打印" countKeep为0"返回0。
据我所知,变量countKeep应该设置为变量count。然后变量count和i对于后续字符串设置为0。然后返回countKeep并在此字符串中显示x的出现。
这个初学者问题我错过了什么?
我通过以下方式调用方法:
Public Class Form2
Private Sub Form2_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
If e.Modifiers = Keys.Alt And e.KeyCode = Keys.F4 Then
e.Handled = True
End If
End Sub
End Class
输出:
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;
}
答案 0 :(得分:1)
在达到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;
}