Java Reference
In-Depth Information
A
BinaryArray
represents arbitrarily long sequences of binary variables.
The private data representation is an array of Boolean variables. For
instance, the representation of the
BinaryArray “TFTTF”
would be an array
of length five storing true, false, true, true, false in array indices 0, 1, 2, 3,
and 4, respectively. The
BinaryArray
class has the following functionality:
3.28
A one-parameter constructor that contains a
String
. Throw an
IllegalArgumentException
if there are illegal characters.
n
A
toString
method.
n
n
A
get
and
set
method to access or change a variable at a particu-
lar index.
n
A
size
method that returns the number of binary variables in
the
BinaryArray
.
Implement the
BinaryArray
class, placing it in a package of your choosing.
PROGRAMMING PROJECTS
3.29
Implement a simple
Date
class. You should be able to represent any date
from January 1, 1800, to December 31, 2500; subtract two dates; incre-
ment a date by a number of days; and compare two dates using both
equals
and
compareTo
. A
Date
is represented internally as the number of
days since some starting time, which, here, is the start of 1800. This
makes all methods except for construction and
toString
trivial.
The rule for leap years is a year is a leap year if it is divisible by 4 and
not divisible by 100 unless it is also divisible by 400. Thus 1800, 1900,
and 2100 are not leap years, but 2000 is. The constructor must check the
validity of the date, as must
toString
. The
Date
could be bad if an incre-
ment or subtraction operator caused it to go out of range.
Once you have decided on the specifications, you can do an imple-
mentation. The difficult part is converting between the internal and exter-
nal representations of a date. What follows is a possible algorithm.
Set up two arrays that are static fields. The first array,
daysTillFirst-
OfMonth
, will contain the number of days until the first of each month in a
nonleap year. Thus it contains 0, 31, 59, 90, and so on. The second array,
daysTillJan1
, will contain the number of days until the first of each year,
starting with
firstYear
. Thus it contains 0, 365, 730, 1095, 1460, 1826,
and so on because 1800 is not a leap year, but 1804 is. You should have
your program initialize this array once using a static initializer. You can
then use the array to convert from the internal representation to the exter-
nal representation.
Search WWH ::
Custom Search