Count Digits in Java

Count the number of digits in a given integer.

BeginnerModule 3: Loop ProgramsExample 7 of 25
count-digits.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter a number: ");
7 int n = sc.nextInt();
8
9 if (n == 0) {
10 System.out.println("Digits = 1");
11 return;
12 }
13
14 n = Math.abs(n);
15 int count = 0;
16 while (n != 0) {
17 count++;
18 n /= 10;
19 }
20
21 System.out.println("Digits = " + count);
22 sc.close();
23 }
24}

Output

Enter a number: 12345
Digits = 5

What's going on

We divide by 10 until the number becomes 0 and count iterations.