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

Complete the getMiddle method that gets the middle character from a word if the

ID: 3754003 • Letter: C

Question

Complete the getMiddle method that gets the middle character from a word if the word length is odd, or the middle character pair if it is even. For example, getMiddle("Java")returns "av". If the word is empty, return the empty string. If it is null, return null.

Complete the following file:

public class Words
{
/**
Gets the middle character or character pair from this word
when possible.
@param word a word
@return the middle character (if the word length is odd) or
middle two characters (if it is even), or the empty string if
the word is empty, or null if it is null.
*/
public String getMiddle(String word)
{
// your work here

}
}

Explanation / Answer

public class Words { /** Gets the middle character or character pair from this word when possible. @param word a word @return the middle character (if the word length is odd) or middle two characters (if it is even), or the empty string if the word is empty, or null if it is null. */ public String getMiddle(String word) { if(word == null) { return null; } else if(word.isEmpty()) { return ""; } else if(word.length() % 2 == 1) { return word.substring(word.length() / 2, (word.length()+1) / 2); } else { return word.substring(((word.length() - 1) / 2), ((word.length() - 1) / 2) + 2); } } }