c. Write a displayLyrics method with the following signature: public void displa
ID: 3711241 • Letter: C
Question
c. Write a displayLyrics method with the following signature: public void displayLyrics(HashMap> map) This method will display the lyrics for the song (in uppercase) stored in the map. Start with an empty array of strings whose size is the number of words in the lyric plus 1 (don't use cell 0). Initialize this array with empty strings (not null). Then, get a set of all of the words stored in the map. For each word, store the word in the array cells corresponding to its word position(s). If a word position is negative, add on an extra newline character to the word when you store the word in the array. Once you finish processing all words that are in the map, iterate through the array and print out each string, and you should see the lyrics appear, line by line. Note that if the original lyrics had blank lines, you won't have these in the reconstructed lyrics. Iterate through the array of words using the enhanced for loop. (Just need a method to compute this)
Explanation / Answer
I need to know the variable name which represents the total number of words in the lyrics. This is not passed to this method, so it means the class containing the displayLyrics() method has as variable which represents the total number of words in the lyrics. Since I don't know the name of that variable, I have used the variable name - numWords. You might see an error on the first line inside this method if the variable name is not correct. You can change it to correct variable name which represents total number of words in the lyrics. Rest of the code works as described in the question. Post a comment if you are confused. I'll help.
public void displayLyrics(HashMap<String, ArrayList<Integer>> map)
{
String[] words = new String[numWords + 1];
for(int i = 0; i < words.length; i++)
words[i] = ""; //initialize with empty strings
for(String w : map.keySet())
{
for(Integer pos : map.get(w))
{
if(pos < 0) //negative value, so its end of line, add
words[-pos] = w + " ";
else
words[pos] = w;
}
}
//display all words
for(int i = 0; i < words.length; i++)
System.out.print(words[i]);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.