简体   繁体   中英

Why does this method print out 347 rather than 3?

Suppose I have the method

public static void whatsIt(int n){
if (n>10)
    whatsIt(n/10);
System.out.print(n%10);
}

and I call whatsIt(347), why does it print 347 instead of 3?

You can step through what it does:

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)

If you want to print 3, use this

public static void whatsIt(int n){ 
    if (n>10) whatsIt(n/10);
    else System.out.print(n%10);
}

Your code works as:

  1. whatsit(347): call whatsit(34), then print 7, then return
  2. whatsit(34): call whatsit(3), then print 4, then return.
  3. whatsit(3): print 3, then return.

Try this:

public static void whatsIt(int n){
if (n>10)
    whatsIt(n/10);
else
    System.out.print(n%10);
}

Because you do not want to print anything if n <= 10.

In your initial code, each recursive call was printing n%10. Therefore the first call, whatsIt(347) , was printing 7 (347 % 10), the second call was printing 4 (34 % 10) and the third call was printing 3 (3 % 10). These would have been printed in reverse order during backtracking giving you 347.

Methods do not stop if they call themselves. When the sub-calls have finished, control flow returns to the "original" method call and continues to the next line, which is the print, and thus prints the original number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM