简体   繁体   中英

Having trouble understanding recursion in Java

import java.util.Scanner; 

public class findFive {

    public static int count = 0;
    public static String result = null;

    public static void main(String[] args) {
        System.out.println("Enter a nonnegative number");
        Scanner input = new Scanner(System.in);

        int number = input.nextInt();
        countFive(number);
        System.out.println(count);
    }

    public static void countFive(int number) {
        if (number < 10) {// the base case
            if (number == 5) {
                count++;
            }
        } else { // number has two or more digits
            countFive(number / 10);
            if (number % 10 == 5) {
                count++;
            }
        }
    }
}

To put it simply, I do not understand the flow of the countFive(int number) method. I know that if the user enters 5 , then the count will simply be equal to 1. However, my confusion comes from where the method is called again inside the method with 'countFive(number/10)'.

EDIT: I would appreciate if someone went through the flow of the code with a number like 552.

If you want to see how this works you should step through the code in your debugger, it will be much more clear when you see it in action

The method is counting how many times the digit 5 occurs in a number. For example if you pass in the number 515 the following will happen

  1. 515 is greater than 10
  2. Call countFive(number/10) which evaluates to countFive(51)
  3. 51 is greater than 10
  4. Call countFive(number/10) which evaluates to countFive(5)
  5. 5 is less than 10
  6. 5 equals 5
  7. Increment count
  8. Step out
  9. number%10 == 5 which evaluates to 1%10 == 5 - False
  10. Step out
  11. number%10 == 5 which evaluates to 5%10 == 5 - True
  12. Increment count

    countFive(515) | 515 greater than 10 | countFive(51) | | 51 greater than 10 | | countFive(5) | | | count++ | | 51 mod 10 does not equal 5 | 515 mod 10 equals 5 | count++

In recursion base case is created to avoid infinite calls to the same method. That is defined by you below.

if (number < 10) {// the base case
   if (number == 5) {
      count++;
   }
}

If this condition is satisfied, execution comes out of this method. If this isn't true, else block is executed.

else { // number has two or more digits
    countFive(number/10);  //This is where it is called again
    if (number%10 == 5) {
       count++;
    }
}

In this you have call to countFive(number/10)

Well, the method counts the occurence of 5 in a number. For example, 5123512356 would return 3 .

You simply use recursion to remove the last digit of the number until you have reached the highest digit ( 5 in the example on the left).

Once you have reached it, it will go into number < 10 and see that it indeed is a 5. Then it will leave the method and continues with 51 (51 % 10 = 1), continues with 512 , 5123 , 51235 ( count++ ) and so on until it is through with the whole number.

To clarify: number/10 is called to reach the highest digit by removing the last digit of the original number until you cannot divide it by 10 any longer. And then the checks go through backwards.

Let's have a look at an easier example: 5050 .

1st call: countFive(5050) . 5050 > 10, so we call:
2nd call: countFive(5050/10) = countFive(505) . Still greater than 10
3rd call: countFive(50)
4th call: countFive(5) : counter++ , the number is smaller than 10 now we go backwards through these three calls (the last one is finished)
3rd call: 50 % 10 = 0, counter stays the same
2nd call: 505 % 10 = 5, counter++
1st call: 5050 % 10 = 0, counter stays the same

Afterwards: counter = 2.

Let's take the input you proposed: 552 and follow the method.

At the beginning count is 0.

number        count     number < 10      number == 5       number % 10 == 5
-----------   -------   --------------   --------------    ------------------
552           0         false            false             false
55            0         false            false             true
              1
5             1         true             true              true
              2

And it'll return 2. Basically as you can see the method counts the number of occurrences of the digit 5 in the input.

Your base case checks if it's a digit ( < 10 ) and if so checks if the digit is 5. Otherwise, it chops the right-most digit and calls the method again, as if the input was that new number. It stops once the number is left with only a single digit.

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