Computer >> Computer tutorials >  >> Programming >> Java

Java Program to Count Number of Digits in an Integer


In this article, we will understand how to count the number of digits in an integer. The digits in an integer is counted using a loop and a counter.

Below is a demonstration of the same −

Input

Suppose our input is −

Number : 15161718

Output

The desired output would be −

The result is : 8

Algorithm

Step 1 - START
Step 2 – Declare two integer values namely my_count and my_input.
Step 3 - Read the required values from the user/ define the values
Step 4 – Using a for loop, divide the input value by 10 until the number is reduced to its
lowest possible value. Increment the counter value each time.
Step 5- Display the counter value as result
Step 6- Stop

Example 1

Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool Java Program to Count Number of Digits in an Integer.

import java.util.Scanner;
public class Main {
   public static void main(String[] args) {
      int my_count , my_input;
      my_count = 0;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the number : ");
      my_input = my_scanner.nextInt();
      for (; my_input != 0; my_input /= 10, ++my_count) {
      }
      System.out.println("The number of digits in the given input is: " + my_count);
   }
}

Output

Required packages have been imported
A reader object has been defined
Enter the number : 15161718
The number of digits in the given input is : 8

Example 2

Here, the integer has been previously defined, and its value is accessed and displayed on the console.

public class Main {
   public static void main(String[] args) {
      int my_count = 0, my_input;
      my_count = 0;
      my_input = 15161718;
      System.out.println("The number is defined as " +my_input);
      for (; my_input != 0; my_input /= 10, ++my_count) {
      }
      System.out.println("The number of digits in the given input is: " + my_count);
   }
}

Output

The number is defined as 15161718
The number of digits in the given input is: 8