[ Team LiB ] Previous Section Next Section

2.9 Exercises

Exercise 2-1. Write a Circle class that is similar to the Rect class. Define a move( ) method and an isInside( ) method. (Recall that a circle is defined as all points within a given radius from the center. Test for insideness by using the Pythagorean theorem to compute the distance between a point and the center of the circle.) Also, define a boundingBox( ) method that returns the smallest Rect that encloses the complete Circle. Write a simple program to test the methods you've implemented.

Exercise 2-2. Write a class that represents a person's mailing address. It should have separate fields for the name, street address, city, state, and ZIP code. Define a toString( ) method that produces nicely formatted output.

Exercise 2-3. Modify the ComplexNumber class of Example 2-5 to override the equals( ) and hashCode( ) methods inherited from Object. Use the IntList class of Example 2-7 as a model.

Exercise 2-4. Modify Example 2-5 again to implement Comparable as Example 2-7 does. Note that this is not as straightforward as its seems, since there is not an unambiguous ordering for complex numbers. One possible way to order complex numbers is by their magnitude. Although this ordering is suitable for some applications, note that it is not compatible with the equals( ) method. That is, a compareTo( ) method based on magnitude will return (equality) for numbers that are nonequal according to the equals( ) method.

Exercise 2-5 . Modify the IntList class of Example 2-7 to create a sort( ) method that rearranges the list elements into sorted order. You can use the sorting algorithm from the SortNumbers class of Example 1-14, or you may prefer to research and implement a more advanced sorting algorithm, such as quicksort or mergesort.

Exercise 2-6. The IntList class implements the Comparable interface, which means that IntList objects can be compared to each other. Write a program that initializes an array of IntList objects, sorts those objects, and then prints the lists in their new order (IntList overrides toString( ), so printing the lists is easy).

    [ Team LiB ] Previous Section Next Section