Count Digits
Count the number of digits in a given integer.
BeginnerTopic: Module 3: Loop Programs
Java Count Digits Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
if (n == 0) {
System.out.println("Digits = 1");
return;
}
n = Math.abs(n);
int count = 0;
while (n != 0) {
count++;
n /= 10;
}
System.out.println("Digits = " + count);
sc.close();
}
}Output
Enter a number: 12345 Digits = 5
Understanding Count Digits
We divide by 10 until the number becomes 0 and count iterations.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.