Java Program to Count Number of Digits in an Integer

In this tutorial, you'll learn how to write a Java program to count the number of digits in an integer.
We will read input from the console using Scanner class.

Java Program to Count Number of Digits in an Integer

package com.javaguides.java.tutorial;

import java.util.Scanner;

/**
 * Java Program to Count Number of Digits in an Integer
 * 
 * @author https://www.sourcecodeexamples.net/
 *
 */
public class JavaProgram {
    public static void main(String[] args) {

        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("Enter the digit :");
            int num = scanner.nextInt();

            int count = 0;

            while (num != 0) {
                num /= 10;
                ++count;
            }
            System.out.println("Number of digits: " + count);
        }
    }
}
Output:
Enter the digit :
12345
Number of digits: 5

Related Java Programs


Comments