Java Reference
In-Depth Information
the music by a particular artist or need to find all the music with a particular phrase in the title.
There is nothing to stop us doing this, because the body of a for-each loop is just an ordinary
block, and we can use whatever Java statements we wish inside it. So using an if-statement in
the body to select the files we want should be easy.
Code 4.4 shows a method to list only those file names in the collection that contain a particular string.
Code 4.4
Printing selected items
from the collection
* List the names of files matching the given search string.
* @param searchString The string to match.
public void listMatching(String searchString)
for (String filename : files) {
if (filename.contains(searchString)) {
// A match.
Using an if statement and the boolean result of the contains method of the String class,
we can “filter” which file names are to be printed and which are not. If the file name does not
match, then we just ignore it—no else part is needed. The filtering criterion (the test in the if
statement) can be whatever we want.
Exercise 4.25 Add the listMatching method in Code 4.4 to your version of the project.
(Use music-organizer-v3 if you do not already have your own version.) Check that the method
only lists matching files. Also try it with a search string that matches none of the file names. Is
anything at all printed in this case?
Exercise 4.26 Challenge exercise In listMatching , can you find a way to print a mes-
sage, once the for-each loop has finished, if no file names matched the search string? Hint:
Use a boolean local variable.
Exercise 4.27 Write a method in your version of the project that plays samples of all the
tracks by a particular artist, one after the other. The listMatching method illustrates the ba-
sic structure you need for this method. Make sure that you choose an artist with more than one
file. Use the playAndWait method of the MusicPlayer, rather than the startPlaying
method; otherwise, you will end up playing all the matching tracks at the same time. The play-
AndWait method plays the beginning of a track (about 15 seconds) and then returns.
Exercise 4.28 Write out the header of a for-each loop to process an ArrayList<Track>
called tracks . Don't worry about the loop's body.
Search WWH ::

Custom Search