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

I need to write a class with the following static methods. wordCount. This metho

ID: 3625637 • Letter: I

Question

I need to write a class with the following static methods.

wordCount. This method should accept a String object as an argument and return the number of words contained in the object.

arrayToString. This method accept a char array as an argument and convert it to a String object. The method should return a reference to the String object.

mostFrequent. This method should accept a String object as an argument and return the characters that occurs most frequently in the object.

replaceSubstring. This method accept three Strings objects as argument. str1,str2, and str3. It searches str1 for all occurrences of st2. When it finds an occurrences of str2, it replaces it with str3.

Explanation / Answer

public static int wordCount(String line)
{
int count = 0;

Scanner chopper = new Scanner(line);

while(chopper.hasNext())
{
chopper.next();
count++;
}

return count;
}

public static String arrayToString(char[] array)
{
String output = "";

for(char c : array)
output += c;
return output;
}

public static char mostFrequent(String line)
{
// count characters
Map<Character, Integer> counts = new TreeMap<Character, Integer>();

for(char c : line.toCharArray())
{
if(counts.containsKey(c))
counts.put(c, counts.get(c)+1);
else
counts.put(c, 1);
}

// search for highest count
int max = 0;
char output = ' ';

for(char c : counts.keySet())
{
if(counts.get(c) > max)
{
max = counts.get(c);
output = c;
}
}

return output;
}

public static String replaceSubstring(String str1, String str2, String str3)
{
return str1.replaceAll(str2, str3);
}