• No results found

System.out.println( new List( ) );

objects and classes

16 17 System.out.println( p ); // illegal

13 System.out.println( new List( ) );

14 }

3.23 Modify the BigRationalclass so that 0/0 is legal and is interpreted as “Indeterminate” by toString.

3.24 Write a program that reads a data file containing rational numbers, one per line, stores the numbers in an ArrayList, removes any dupli- cates, and then outputs the sum, arithmetic mean, and harmonic mean of the remaining unique rational numbers.

3.25 Suppose you would like to print a two dimensional array in which all numbers are between 0 and 999. The normal way of outputting each number might leave the array misaligned. For instance:

54 4 12 366 512 756 192 18 27 4 14 18 99 300 18

Examine the documentation for the format method in the String class and write a routine that outputs the two-dimensional array in a nicer format, such as

54 4 12 366 512 756 192 18 27 4 14 18 99 300 18

3.26 Package java.math contains a class BigDecimal, used to represent an arbitrary-precision decimal number. Read the documentation for

BigDecimal and answer the following questions: a. Is BigDecimal an immutable class?

b. Ifbd1.equals(bd2) is true, what is bd1.compareTo(bd2)? c. If bd1.compareTo(bd2) is 0, when is bd1.equals(bd2) false?

d. If bd1 represents 1.0 and bd2 represents 5.0, by default what is

bd1.divide(bd2)?

e. If bd1 represents 1.0 and bd2 represents 3.0, by default what is

bd1.divide(bd2) ?

f. What is MathContext.DECIMAL128?

g. Modify the BigRational class to store a MathContext that can be initialized from an additional BigRational constructor (or which defaults to MathContext.UNLIMITED). Then add a toBigDecimal

method to the BigRational class.

3.27 An Account class stores a current balance, and provides getBalance,

deposit, withdraw, and toString methods in addition to at least one constructor. Write and test an Accountclass. Make sure your withdraw method throws an exception if appropriate.

3.28 ABinaryArrayrepresents 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 BinaryArrayclass has the following functionality:

n A one-parameter constructor that contains a String. Throw an

IllegalArgumentException if there are illegal characters.

n AtoString method.

n Agetandsetmethod to access or change a variable at a particu- lar index.

n A size method that returns the number of binary variables in theBinaryArray.

Implement the BinaryArrayclass, placing it in a package of your choosing.

PROGRAMMING PROJECTS

3.29 Implement a simple Dateclass. 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

equalsandcompareTo. A Dateis 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 Datecould 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.

3.30 APlayingCardrepresents a card used in games such as poker and black jack, and stores the suit value (hearts, diamonds, clubs, or spades) and the rank value (2 through 10, or jack, queen, king, or ace). A Deckrep- resents a complete 52-card collection of PlayingCards. A MultipleDeck

represents one or more Decksof cards (the exact number is specified in the constructor). Implement the three classes PlayingCard,Deck, and

MultipleDeck, providing reasonable functionality for PlayingCard, and for both DeckandMultipleDeck, minimally provide the ability to shuf- fle, deal a card, and check if there are remaining cards.

3.31 A complex number stores a real part and an imaginary part. Provide an implementation of a BigComplexclass, in which the data representa- tion is two BigDecimals representing the real and imaginary parts. 3.32 Sometimes a complex number is represented as a magnitude and an angle

(in the half-open range of 0 to 360 degrees). Provide an implementation of a BigComplexclass, in which the data representation is one BigDecimal

representing the magnitude and a double representing the angle.

3.33 Implement a class, Polynomial, to represent single-variable polynomi- als and write a test program. The functionality of the Polynomialclass is as follows:

n Provide at least three constructors: a zero-parameter constructor that makes the polynomial zero, a constructor that makes a sepa- rate independent copy of an existing polynomial, and a construc- tor that creates a polynomial based on a Stringspecification. The last constructor can throw an exception if the Stringspecification is invalid, and you can make a design decision on what a valid specification is.

n negate returns the negative of this polynomial.

n add, subtract, and multiply return a new polynomial that is the sum, difference, or product, respectively, of this polynomial and another polynomial, rhs. None of these methods change either of the original polynomials.

n equals andtoStringfollow the standard contract for these func- tions. For toStringmake the String representation look as nice as you can.

n The polynomial is represented by two fields. One, degree, repre- sents the degree of the polynomial. Thus x2+2x +1 is degree 2, 3x + 5 is degree 1, and 4 is degree 0. Zero is automatically degree 0. The second field, coeff, represents the coefficients (coeff[i] represents the coefficient of xi).

3.34 Modify the class in the previous exercise to store the coefficients as

BigRationals.

3.35 Implement a complete IntType class that supports a reasonable set of constructors, add, subtract, multiply, divide, equals, compareTo, and

toString. Maintain an IntType as a sufficiently large array. For this class, the difficult operation is division, followed closely by multiplication.

references

More information on classes can be found in the references at the end of Chapter 1. The classic reference on design patterns is [1]. This book describes 23 standard patterns, some of which we will discuss later.