Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

For this I have already created the class whose constructor takes a string as in

ID: 3622906 • Letter: F

Question

For this I have already created the class whose constructor takes a string as input and creates an integer array of how many of each letter are in the input word. For example, if the input word were "school" the integer array (called charCount, which is of size 26) would have charCount[18] = 1 (the letter s) , charCount[14] = 2 (the letter o) and so forth. How would one make a method (called toString, which would return a string) that would create a bracketed version of the letters? For example, an inventory of 3 c's, 2 d's and 4 e's would print "[cccddeeee]".

Explanation / Answer

int[] charCount;

public String toString()
{
String output = "[";

// for each letter
for(int i = 0; i < charCount.length; i++)
{
// add letter for each count
for(int j = 0; j < charCount[i]; j++)
{
output += (char)('a'+i);
}
}
return output;
}