Ex:
Write a program that creates a char type array of 100 lowercase letters randomly and counts the occurrence of each letter in the array.
JAVA Code:
Write a program that creates a char type array of 100 lowercase letters randomly and counts the occurrence of each letter in the array.
package javaapplication3;
import java.util.Arrays;
import java.util.Random;
public class JavaApplication3
{
public static void main(String[] args)
{
// TODO code application logic here
JavaApplication3 obj=new JavaApplication3();
Random o=new Random();
int max=122,min=97;
char arr[]=new char[100];
for(int i=0;i<100;i++)
{
int n= o.nextInt((max-min)+1);
n=n+min;
arr[i]=(char)n;
}
System.out.println("Hundred Random letters:");
for(int i=0;i<100;i++)
{ if(i==20 || i==40 || i==60 || i==80)
{System.out.print("\n");}
System.out.print(" "+arr[i]);
}
int occ[]=new int[26];
Arrays.fill(occ, 0);
System.out.print("\n");
System.out.println("Occurrence of each letter:\n");
obj.fintoccurrence(arr,occ);
}
void fintoccurrence(char arr[],int occ[])
{
for(int i=0;i<100;i++)
{
int oc= arr[i]-97;
occ[oc]++;
}
int as=97;
for(int i=0;i<26;i++)
{ if(i==10 || i==20)
{ System.out.print("\n"); }
System.out.print("\t"+occ[i]+" "+(char)as);
as++;
}
}
}
No comments:
Post a Comment