Source of TestCountDigitsRecursively.java


  1: //TestCountDigitsRecursively.java

  3: import java.util.Scanner;

  5: public class TestCountDigitsRecursively
  6: {
  7:     public static void main(String[] args)
  8:     {
  9:         Scanner keyboard = new Scanner(System.in);
 10:         System.out.println("\nThis program reads in a positive integer "
 11:             + "and then computes\nand prints out the number of digits "
 12:             + "it contains.\n");
 13:         boolean finished = false;
 14:         do
 15:         {
 16:             System.out.print("Enter a positive integer: ");
 17:             int n = keyboard.nextInt();
 18:             keyboard.nextLine();
 19:             System.out.print("The number of digits in " + n
 20:                 + " is " + numberOfDigits(n) + ".\n\n");
 21:             System.out.print("Do it again? (y/[n]) ");
 22:         }
 23:         while (keyboard.nextLine().equalsIgnoreCase("y"));
 24:     }

 26:     public static int numberOfDigits
 27:     (
 28:         int n
 29:     )
 30:     /**
 31:     Compute the number of digits in a positive integer.
 32:     @return The number of digits in the integer n.
 33:     @param n The integer whose digits are to be counted.
 34:     @post n has been initialized with a positive integer.
 35:     @post No other side effects.
 36:     */
 37:     {
 38:         if (n < 10)
 39:             return 1;
 40:         else
 41:             return 1 + numberOfDigits(n / 10);
 42:     }
 43: }