Home »
Java Programs »
Java Class and Object Programs
Java program to count digits of a number using class
In this program, we will read a positive integer number and find the count of all digits using a class. For example, if the input number is 12345 - the count of all digits will be 5.
Example:
Input:
12345
Output:
5
Input:
123
Output:
3
Program:
// Java program to count total number of
// digits using class
import java.util.*;
class DigitsOpr {
private int num;
//function to get value of num
public void getNum(int x) {
num = x;
} //End of getNum()
//function to count total digits
public int countDigits() {
int n, count;
n = num; //keep value of num safe
count = 0; //reset counter
while (n > 0) {
n /= 10;
count++;
}
return count;
} //End of countDigits()
}
public class number {
public static void main(String[] s) {
DigitsOpr dig = new DigitsOpr();
int n;
Scanner sc = new Scanner(System.in);
//read number
System.out.print("Enter a positive integer number: ");
n = sc.nextInt();
dig.getNum(n);
System.out.println("Total number of digits are: " + dig.countDigits());
}
}
Output
Enter a positive integer number: 12345
Total number of digits are: 5
Java Class and Object Programs »