public class DigitCounter
{
public static void main(String[] args)
{
int no = 1382;
int count = 0;
while (no != 0)
{
no = no / 10;
count++;
}
System.out.println("The number of digits is: " + count);
}
}
The number of digits is: 4
import java.util.Scanner;
public class DigitCounter
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int no = scanner.nextInt();
int count = 0;
while (no != 0)
{
no = no / 10;
count++;
}
System.out.println("The number of digits is: " + count);
scanner.close();
}
}
Enter a number: 72513 The number of digits is: 5
Scanner
and store it in an integer variable no
.
count = 0
. This variable will track the number of digits.
no
becomes 0.
no
by 10 (no = no/10;
) to remove the last digit.
count
by 1 (count++
) to record that a digit has been counted.
count
variable will hold the total number of digits in the input number.
System.out.println("The number of digits is: " + count);
.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.