Thursday, March 17, 2011

BlueJ Program On Counting Digits Frequency In A Number

This is a program on BlueJ for counting digits frequency In a number.

Codes of the program



import java.io.*;
class Digits
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,zero=0,one=0,two=0,three=0,four=0,five=0,six=0,seven=0,eight=0,nine=0,n;
public void show() throws Exception
{
System.out.println("Enter the number:");
n=Integer.parseInt(br.readLine());
while(n >0)
{
i=n%10;
switch(i)
{
case 0:
zero++;
break;
case 1:
one++;
break;
case 2:
two++;
break;
case 3:
three++;
break;
case 4:
four++;
break;
case 5:
five++;
break;
case 6:
six++;
break;
case 7:
seven++;
break;
case 8:
eight++;
break;
case 9:
nine++;
break;
}
n=n/10;
}
if(zero!=0)
System.out.println("Zero digit="+zero);
if(one!=0)
System.out.println("One digit="+one);
if(two!=0)
System.out.println("Two digit="+two);
if(three!=0)
System.out.println("Three digit="+three);
if(four!=0)
System.out.println("Four digit="+four);
if(five!=0)
System.out.println("Five digit="+five);
if(six!=0)
System.out.println("Six digit="+six);
if(seven!=0)
System.out.println("Seven digit="+seven);
if(eight!=0)
System.out.println("Eight digit="+eight);
if(nine!=0)
System.out.println("Nine digit="+nine);
}
public static void main(String args[]) throws Exception
{
Digits ob=new Digits ();
ob.show();
}
}

Related PostBlueJ Programs on Number

Technical analysis of this program



This program needs 10 counter variables for counting the frequency of each digit as the number may contain any digits among the 10 digits available in decimal number system. Take the number and access each digit from the number. Using ‘switch’, the digit is checked and the appropriate counter is incremented.

The next step in this program is to display the counters. All the counters are not displayed as in a number all the digits may not be present. So the counter variables are checked and if it is not zero then the value of the variable is displayed.

2 comments:

  1. I think using arrays may reduce the length of the code..

    ReplyDelete
  2. Correct and I will post the program very soon

    ReplyDelete

Subscribe via email

Enter your email address:

Delivered by FeedBurner