Source of TestCountDigitsIteratively.java


  1: //TestCountDigitsIteratively.java

  3: import java.util.Scanner;

  5: public class TestCountDigitsIteratively
  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:         int digitCount = 0;
 32:         while (n > 0)
 33:         {
 34:             n = n/10;
 35:             ++digitCount;
 36:         }
 37:         return digitCount;
 38:     }
 39: }