![](/img/trans.png)
[英]Why does my method that scans a file and prints out the result print 1 space further than the last time?
[英]Why does this method print out 347 rather than 3?
假設我有這個方法
public static void whatsIt(int n){
if (n>10)
whatsIt(n/10);
System.out.print(n%10);
}
我打電話給它(347),為什么打印347而不是3?
你可以逐步完成它的工作:
whatsIt(347)
- is 347 > 10? yes
-- whatsIt(34)
--- is 34 > 10? yes
---- whatsIt(3)
----- is 3 > 10? no
----- print 3 % 10 (-> 3)
--- print 34 % 10 (-> 4)
- print (347 % 10) (-> 7)
如果要打印3,請使用此選項
public static void whatsIt(int n){
if (n>10) whatsIt(n/10);
else System.out.print(n%10);
}
您的代碼如下:
嘗試這個:
public static void whatsIt(int n){
if (n>10)
whatsIt(n/10);
else
System.out.print(n%10);
}
因為如果n <= 10,您不想打印任何內容。
在您的初始代碼中,每個遞歸調用都打印n%10。 因此,第一個電話, whatsIt(347)
,打印7(347%10),第二個電話打印4(34%10),第三個電話打印3(3%10)。 這些將在回溯過程中以相反的順序打印,從而給您347。
如果他們自稱,方法不會停止。 當子調用完成后,控制流程返回到“原始”方法調用並繼續到下一行,即打印,從而打印原始編號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.