Java Reference
In-Depth Information
Exercise 4.14
Add a method called
checkIndex
to the
MusicOrganizer
class. It takes
a single integer parameter and checks whether it is a valid index for the current state of the col-
lection. To be valid, the parameter must lie in the range
0
to
size()-1
.
If the parameter is not valid, then it should print an error message saying what the valid range
is. If the index is valid, then it prints nothing. Test your method on the object bench with both
valid and invalid parameters. Does your method still work when you check an index if the col-
lection is empty?
Exercise 4.15
Write an alternative version of
checkIndex
called
validIndex
. It takes
an integer parameter and returns a boolean result. It does not print anything, but returns
true
if
the parameter's value is a valid index for the current state of the collection and
false
otherwise.
Test your method on the object bench with both valid and invalid parameters. Test the empty
case too.
Exercise 4.16
Rewrite both the
listFile
and
removeFile
methods in
MusicOrganizer
so that they use your
validIndex
method to check their parameter, instead of the current
boolean expression. They should only call
get
or
remove
on the
ArrayList
if
validIndex
returns
true
.
4.8
Playing the music files
It would be a nice feature of our organizer if it not only kept a list of music files but also al-
lowed us to play them. Once again, we can use abstraction to help us here. If we have a class
that has been written specifically to play audio files, then our organizer class would not need to
know anything about how to do that; it could simply hand over the name of the file to the player
class and leave it to do the rest.
Unfortunately, the standard Java library does not have a class that is suitable for playing MP3
files, which is the audio format we want to work with. However, many individual programmers
are constantly writing their own useful classes and making them available for other people to
use. These are often called “third-party libraries,” and they are imported and used in exactly the
same way as are standard Java library classes.
For the next version of our project, we have made use of a set of classes from
javazoom.net
to write our own music-player class. You can find this in the version called
music-organizer-v2
.
The three methods of the
MusicPlayer
class we shall be using are
playSample
,
start-
Playing
, and
stop
. The first two take the name of the audio file to play. The first plays
some seconds of the beginning of the file and returns when it has finished playing, while
the second starts its playing in the background and then immediately returns control back
to the organizer—hence the need for the
stop
method, in case you want to cancel playing.
Code 4.2 shows the new elements of the
MusicOrganizer
class that access some of this
playing functionality.
Search WWH ::
Custom Search