Find Frequency of Each Digit in Java

A class Number has been defined to find the frequency of each digit present in it and the sum of the digit and to display the results.

Some of the members of the class Number are given below:

Class name: Number
Data member:
num: integer variable to store the number.
Member functions:
Number(int n): constructor to assign n to num.
void frequency(): to find the frequency of each digit and to display it.
int sum(): to return the sum of the digits of the number.

Specify the class Number, giving details of the constructor and functions frequency() and sum(). You do not need to write the main() function.

Program:

import java.io.*;
class Number{
    private int num;
    public Number(int n){
        num = n;
    }
    public void frequency(){
        for(int i = 0; i <= 9; i++){ 
            int count = 0; 
            for(int j = num; j != 0; j /= 10){ 
                int digit = j % 10; 
                if(i == digit) 
                    count++; 
            } 
            if(count > 0){
                System.out.println(i + " - " + count + " time(s).");
                count = 0;
            }
        }
    }
    public int sum(){
        int s = 0;
        for(int i = num; i != 0; i /= 10){
            s = s + i % 10;
        }
        return s;
    }
}

Leave a Reply