Java Program to Count Digits of a Number

Here is a simple Java program that counts the number of digits in a given integer:

Problem

Here is example of the problem  –

Enter an Number : 12345
Number of digits in 12345 : 5

Algorithm:

  1. Start program,
  2. Read or input a number,
  3. declare an integer variable count initialize it with 0,
  4. Divide the number with 10 till the number is 0, and for each turn increase the count.

Code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import java.util.Scanner;
public class NumberOfDigits {
public static void main(String[] args) {
int Number;
int count=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter any Number: ");
Number = sc.nextInt();
while(Number > 0) {
Number = Number / 10;
count++;
}
System.out.println("Number of digits in a given number is "+count);
}
}
import java.util.Scanner; public class NumberOfDigits { public static void main(String[] args) { int Number; int count=0; Scanner sc = new Scanner(System.in); System.out.println("Enter any Number: "); Number = sc.nextInt(); while(Number > 0) { Number = Number / 10; count++; } System.out.println("Number of digits in a given number is "+count); } }
import java.util.Scanner;

public class NumberOfDigits {	
    public static void main(String[] args) {
        int Number;
        int count=0;
         Scanner sc = new Scanner(System.in);		
        System.out.println("Enter any Number: ");
        Number = sc.nextInt();
        
        while(Number > 0) {
            Number = Number / 10;
            count++;
        }
        System.out.println("Number of digits in a given number is  "+count);
    }
}

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Enter any Number:
1234
Number of digits in a given number is 4
Enter any Number: 1234 Number of digits in a given number is 4
 Enter any Number: 
1234
Number of digits in a given number is 4

More java Programs:

Leave a Comment

%d bloggers like this:
Python4U
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.