Write a Java program that reads an positive integer and count the number of digits


The program starts by importing the Scanner class, which is used to read input from the user. The main method then creates a new Scanner object and prompts the user to enter a long integer using System.out.print() and in.nextLong().

The program then checks whether the input is a long integer using in.hasNextLong(). If the input is a long integer, the program proceeds to count the number of digits in the integer.

To count the number of digits, the program uses a series of if statements that check whether the integer is within a certain range of values. Each range corresponds to a certain number of digits, and the program uses a variable digits to store the number of digits in the integer.

Finally, the program prints the number of digits in the integer using System.out.println().

Source Code

import java.util.Scanner;
class PosNeg_Count
{
 
   public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter The Lessthan Ten Digits : "); 
		if (in.hasNextLong())
		{
 
			long num = in.nextLong();
 
			if (num < 0)
			{
				num *= -1;
			}          
			{
				int digits = 1;
				if (num >= 10 && num < 100)
				{
					digits = 2;
				}
				else if (num >= 100 && num < 1000)
				{
					digits = 3;
				}
				else if (num >= 1000 && num < 10000)
				{
					digits = 4;
				}
				else if (num >= 10000 && num < 100000)
				{
					digits = 5;
				}
				else if (num >= 100000 && num < 1000000)
				{
					digits = 6;
				}
				else if (num >= 1000000 && num < 10000000)
				{
					digits = 7;
				}
				else if (num >= 10000000 && num < 100000000)
				{
					digits = 8;
				}
				else if (num >= 100000000 && num < 1000000000)
				{
					digits = 9;
				}
				else if (num >= 1000000000 && num < 10000000000L)
				{
					digits = 10;
				}
				System.out.println("Number of digits in the number: " + digits);
			}
		}
		else
		{
			System.out.println("The number is not an integer");
		}
    }
}

Output

Enter The Lessthan Ten Digits : 123425533
Number of digits in the number: 9

Enter The Lessthan Ten Digits : 41-454-7
The number is not an integer

Example Programs