Try this problem before you look at the answers. This is a particularly good problem to discuss with other students, perhaps as part of a study group.
The end of lab 1 included an additional problem that involved creating a class for Albums and having each Song contain a object for its album. Here, we restate that problem, along with exercises to write two methods about Songs and Albums.
We also show you an attempted solution (as might have been written by a classmate). Critique that attempt, looking for mistakes in Java syntax, usage of Java operators, and poor choices in structuring the classes or methods. The goal is not for you to write the code yourself, though you may of course do that if you want additional practice.
Why Critique Code? Studies have shown that writing and reading code are two very different skills. The goal of this exercise is to help reinforce aspects of writing good Java programs that you might have overlooked or not encountered in just writing your own code from scratch. Feel free to come to office hours to go over any of your observations or questions about the issues raised in the answers document.
Songs are typically affiliated with Albums. We want to add an Album class and include a field with album information in each Song.
Define a class for albums, which contain two strings. One is the name of the artist; the other is the genre of music ("Rock", "Jazz", etc) that is on the album.
Edit your Song class to include a field onAlbum with type Album.
Revise your examples of Song data to include the new Album field.
Write a method called onSameAlbum that determines whether two Songs are on the same album (returning a boolean).
Add a method hasRockMusic to the Album class that determines whether the album’s genre is "rock".
Add some test cases.
Look at this sample attempt at adding the Album class and writing the two methods described above: (as Java for experimenting or as PDF for marking up). (If you download the Java code to experiment with in a programming environment, you’ll need to separate the Examples class into a separate file.)
What errors do you see? (try doing this without running the code first)
What do you have to remember about programming in Java to avoid these mistakes?
What error messages does Java produce for these mistakes? (run the code to find out – the errors don’t always make sense, but this exercise is designed to help you recognize having seen these messages before, in case they arise again in your own work).
This document reviews several issues with the attempted solution. Follow up on the forum or in office hours with any questions on these.