Hey Chegg, I am currently looking for a solution for this problem in Java: Pleas
ID: 3903517 • Letter: H
Question
Hey Chegg,
I am currently looking for a solution for this problem in Java:
Please add comments to the code:
Describe the purpose of every variable
Explain the algorithm you are using for solution
Add proper comments for all methods. Include @param, @return, and @throws tags
Thank you!
Characters of a String Write a static method that takes a string as argument, then prints out a table: for eaclh character that occurs in the string, the table contains the character and its frequency of occurrence. Assume that the string contains only ASCII characters. Sample string: Alex A Output: A 2 Suggested approach: Create an array of short integers, where each element is holding frequency of occurrence of a character with specific character code. The element of the array is associated with the character ASCII code via element index, for example element with index 65 is holding the frequency of character A. Use the array as storage for the frequencies of the characters, incrementing the corresponding frequency each time you encounter the character in the given string.Explanation / Answer
class Main {
static void frequency(String a)
{
// since ASCII characters range from 0 to 255
// creating f to hold frequency of that character
int[] f = new int[256];
// looping through each charcter in the string a
for(int i=0; i<a.length(); i++)
{
// if it is a valid ASCII character
if(a.charAt(i) < 256 && a.charAt(i) >= 0)
// incrementing it's increment by 1
f[a.charAt(i)]++;
}
// looping through frequency
for(int i=0; i<f.length; i++)
{
// if it is not 0, printing
if(f[i] != 0)
System.out.printf("%c %d ",i,f[i]);
}
}
public static void main(String[] args) {
frequency("Alex A.");
}
}
/*SAMPLE OUTPUT
1
. 1
A 2
e 1
l 1
x 1
*/