Hey Chegg, I am currently looking for a solution for this problem in Java: Pleas
ID: 3903544 • 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!
Sentence Capitalizer Write a static method that accepts a String object as an argument and capitalizes the first character of each sentence in the string. In addition it removes all extra white spaces between words. For instance, if the string argument is "hello. my Joe. what is your name?" the method should manipulate the string so it contains "Hello. My name is Joe. What is your name?" Assume that period, question mark, and exclamation mark are the only signals of the sentence ending. Suggestion: convert the String into a StringBuilder object to make string modification name1S easier Test the new method in main. Requirement: Make sure to pass through the string only once. Do not use nested loops Name your file SentenceCapitalizer.javaExplanation / Answer
Algorithm For Capitalizing First Letter of Each Word in String
Program
public class SentenceCapitalizer {
public static void main(String[] args)
{
String text = "hello. my name is Joe. what is your name?";
int pos = 0;
boolean capitalize = true;// Flag to keep track if last visited character is a white space or not
StringBuilder sb = new StringBuilder(text);//Convert string to string builder object
while (pos < sb.length()) { //Iterate over the string from beginning to end
if (sb.charAt(pos) == '.')
{ //Check if starting of new sentence
capitalize = true;
}
else if (capitalize && !Character.isWhitespace(sb.charAt(pos)))
//Check If its a character between ‘a’ to ‘z’ (not a white space) and flag capitalize is true
{
sb.setCharAt(pos, Character.toUpperCase(sb.charAt(pos))); // Character need to be converted to uppercase
capitalize = false;
}
pos++;
}
String before = sb.toString();
String after = before.trim().replaceAll(" +", " ");//trim() returns a copy of the string, with leading and trailing whitespace omitted.
System.out.println(after);
}
}
Output
Hello. My name is Joe. What is your name?