The following program demonstrates how to Find the Frequency of Each Digit of a Number in Java.
In this program, first, we convert the number to a string. After that, we create an array of characters by using the characters of the string. Further, we create an ArrayList of the objects of the class CharFrequencies that hold a character and its frequency and assign an object of CharFrequencies that contains the first character and its frequency initialized to 1. Then, we search the Array List for each character in the character array. When the corresponding character is found, its frequency is incremented by 1. In case, the end of the array is reached and the character is not found, insert that character along with a frequency of 1 as a CharFrequencies object in the ArrayList. Finally, display the ArrayList using an Iterator object.
import java.util.*;
public class Frequencies
{
public static void main(String[] args)
{
findFrequencies(223121);
findFrequencies(9813);
findFrequencies(87889);
findFrequencies(666444);
}
public static void findFrequencies(int n)
{
System.out.println("Number = "+n+"\nFrequencies: ");
String str=Integer.toString(n);
char[] ch=new char[str.length()];
for(int i=0;i<str.length();i++)
{
ch[i]=str.charAt(i);
//System.out.print(ch[i]+" ");
}
ArrayList<CharFrequencies> list=new ArrayList<CharFrequencies>();
try{
list.add(new CharFrequencies(ch[0], 1));
//System.out.println(list.get(0).getC()+" "+list.get(0).getF());
for(int i=1;i<ch.length;i++)
{
boolean found=false;
char c1=ch[i];
Iterator<CharFrequencies> it =list.iterator();
while (it.hasNext()) {
CharFrequencies cob = it.next();
if (cob.getC() == c1) {
cob.f++;
found=true;
}
}
if(!found)
{
list.add(new CharFrequencies(ch[i], 1));
}
}
}catch(Exception e){ System.out.println(e.getMessage());
}
Iterator<CharFrequencies> it1 =list.iterator();
while (it1.hasNext()) {
CharFrequencies cob = it1.next();
System.out.println(cob.getC()+" "+cob.getF());
}
}
}
CharFrequencies Class
class CharFrequencies
{
public char c;
public int f;
public CharFrequencies(char c, int f)
{
this.c=c;
this.f=f;
}
public char getC()
{
return this.c;
}
public int getF()
{
return this.f;
}
}
Output