How to count characters from a set of variables in Java?

0 Comments

In the below code, I generate a set or array of random variables and then I am counting every individual character so in through this program we can identify the occurrence of each character.

To generate Random numbers we will use a random library of Java to generate random alphabets

// Main Code

char []array=Random();
for (int i=0;i<array.length;i++)
{
System.out.println(array[i]);
}
for( char alphabet = 'a' ; alphabet <= 'z' ; alphabet++ )
{
int result=count(array, alphabet);
System.out.println(alphabet + " is " + result);
}



// Creating two methods; Random method to generate random numbers and Count method to get the count of partiular variable

public static char[] Random()  //return char array
{
char []array= new char[100];
for (int i=0;i<array.length;i++)
{
array[i]=(char)('a'+ Math.random()* ('z'-'a'+1));
}
return array;
}

public static int count(char[]array, char alphabet) //return count of individual character
{
int count=0;
for (int i=0;i<array.length;i++)
{
if(array[i] == alphabet)
count++;
}
return count;
}


Leave a Reply

Your email address will not be published.