[英]Confusion about program output
public class Main {
public static void main(String[] args) {
pop1(1234);
}
public static void pop1(int x){
System.out.print(x % 10);
if ((x / 10) != 0){
pop1(x/10);
}
System.out.print(x % 10);
}
}
Output : 43211234 输出:43211234
I dont understand the output. 我不明白输出。 First past '4321' is ok; 先读“ 4321”还可以; but how last part '1234' is generated? 但是最后一部分“ 1234”是如何生成的?
The last System.out.print(x % 10);
最后一个System.out.print(x % 10);
--> This line causes the values 1,2,3,4
to be printed. ->此行将导致打印值1,2,3,4
。 This is the last line of each method call. 这是每个方法调用的最后一行。
While entering X:4->3->2->1
(now printing starts here) 1 is printed, then stack unwinds (method returns), then 2 prints and so on.. 输入X:4->3->2->1
(现在开始从此处开始打印)时,先打印1,然后展开纸卷(返回方法),然后打印2张,依此类推。
The second print is called when the pop1 function returns from the recursion - that is the reason the other four numbers are printed in reverse order. 当pop1函数从递归中返回时,第二个打印被调用-这就是其他四个数字以相反顺序打印的原因。 Remove it and you'll be fine. 删除它就可以了。
The first call to: 首次致电:
System.out.print(x % 10);
generates the reverse number 4321
while the second call generates the direct order 1234
. 生成反向号码4321
而第二个调用生成直接命令1234
。 So remove on of the lines if you need only direct/reverse order. 因此,如果仅需要直接/反向顺序,则删除其中的几行。
So you get a direct order 1234
from the second print()
call because it's executed after the recursion call ie innermost recursion call prints 1
at first place while the outermost call prints 4
at the last place. 因此,您从第二个print()
调用中获得直接命令1234
,因为它是在递归调用之后执行的,即最里面的递归调用首先打印1
,最外面的递归打印最后4
。
To visualize what happen you might amend the code like this 为了可视化发生了什么,您可以像这样修改代码
public class Main {
public static void main(String[] args) {
pop1(1234);
}
public static void pop1(int x){
System.out.println("enter: " + x % 10);
if ((x / 10) != 0){
pop1(x/10);
}
System.out.println("leave: " + x % 10);
}
}
produced output 生产的产出
enter: 5
enter: 4
enter: 3
enter: 2
enter: 1
leave: 1
leave: 2
leave: 3
leave: 4
leave: 5
combine this output with the answer from @TheLostMind and you will understand how the code is working. 将此输出与@TheLostMind的答案结合起来,您将了解代码的工作方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.