Task: Write a Java Program to Count Digits of Number
The source of Java Program to Count digits of a number input by the user at run time is:
/* * Write a Java program to input a number and count its digit */ package countdigits; /** * @author www.EasyCodeBook.com */ import java.util.Scanner; public class CountDigits { public static void main(String[] args) { int count = 0, num, n ; Scanner input = new Scanner(System.in); System.out.print("Enter a number to count its digits:"); n = input.nextInt(); num = n; while(num != 0) { num = num/10; count++; } System.out.println("Number of digits: " + count); } }
Sample run and output of the Java Program to count digits in a number provided by the user during program execution is:
Enter a number to count its digits:123456
Number of digits: 6