In this Java program, you’ll learn how to count the number of digits in an Integer. This post explains two ways to count the number of digits in an integer: while
and for
loop
Here are the examples to count the number of digits in an integer in Java.
In this program, you will see how to count the number of digits in an integer using a while
loop.
// Java Program to Count Number of Digits in an Integer using While Loop
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
int count = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = sc.nextInt();
// closing scanner class(not compulsory, but good programming practice)
sc.close();
while (num != 0) {
// num = num/10
num /= 10;
++count;
}
System.out.println("Number of digits in the entered integer are: " + count);
}
}
Enter a number:
00564646554
Number of digits in the entered integer are: 9
In this program, you will see how to count the number of digits in an integer using for
loop.
//Java Program to Count Number of Digits in an Integer using For Loop
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
int count = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = sc.nextInt();
// closing scanner class(not compulsory, but good programming practice)
sc.close();
for (; num != 0; num /= 10, ++count) {
}
System.out.println("Number of digits in the entered integer are: " + count);
}
}
Enter a number:
5432134
Number of digits in the entered integer are: 7
Comments