Java How to Program习题_第八章_深入理解类和对象(Classes and Objects: A Deeper Look)

这章的习题除了最后一个案例外,都已完成。先给自己鼓个掌!

一些有标题的习题,如复数(Complex Numbers)、有理数(Rational Numbers)、井字棋游戏(Tic-Tac-Toe)的源码都已分享。可通过使用“搜博主文章”功能(需访问博客主页)进行快速查询,顺便给这个功能点个赞,搜索结果很准确!

Java How to Program习题_第八章_深入理解类和对象(Classes and Objects: A Deeper Look)_第1张图片

Self-Review Exercises  

8.1 Fill in the blanks in each of the following statements:

a) A(n) static import on demand imports all static members of a class.

b) String class static method format is similar to method System.out.printf, but returns a formatted String rather than displaying a String in a command window. 

c) If a method contains a local variable with the same name as one of its class’s fields, the local variable shadows the field in that method’s scope. 

d) The public methods of a class are also known as the class’s public services or interfaces. 

e) A(n) single-type-import declaration specifies one class to import. 

f) If a class declares constructors, the compiler will not create a(n) no-argument constructor. 

g) An object’s toString method is called implicitly when an object appears in code where a String is needed. 

h) Get methods are commonly called accessor or query method.

i) A(n) predicate method tests whether a condition is true or false. 

j) For every enum, the compiler generates a static method called values that returns an array of the enum’s constants in the order in which they were declared. 

k) Composition is sometimes referred to as a(n) has-a relationship. 

l) A(n) enum declaration contains a comma-separated list of constants. 

m) A(n) static variable represents classwide information that’s shared by all the objects of the class. 

n) A(n) single-type-import declaration imports one static member. 

o) The principle of least privilege states that code should be granted only the amount of privilege and access that it needs to accomplish its designated task. 

p) Keyword final specifies that a variable is not modifiable after initialization in a declaration or constructor. 

q) A(n) type-import-on-demand declaration imports only the classes that the program uses from a particular package.

 r) Set methods are commonly called mutator because they typically change a value. 

s) Use BigDecimal class to perform precise monetary calculations. 

t) Use the throw statement to indicate that a problem has occurred.

Exercises

8.2 (Based on Section 8.14) Explain the notion of package access in Java. Explain the negative aspects of package access.

8.3 What happens when a return type, even void, is specified for a constructor?

8.4 (Rectangle Class) Create a class Rectangle with attributes length and width, each of which defaults to 1. Provide methods that calculate the rectangle’s perimeter and area. It has set and get methods for both length and width. The set methods should verify that length and width are each floating-point numbers larger than 0.0 and less than 20.0. Write a program to test class Rectangle.

8.5 (Modifying the Internal Data Representation of a Class) It would be perfectly reasonable for the Time2 class of Fig. 8.5 to represent the time internally as the number of seconds since midnight rather than the three integer values hour, minute and second. Clients could use the same public methods and get the same results. Modify the Time2 class of Fig. 8.5 to implement the time as the number of seconds since midnight and show that no change is visible to the clients of the class.

8.6 (Savings Account Class) Create class SavingsAccount. Use a static variable annualInterestRate to store the annual interest rate for all account holders. Each object of the class contains a private instance variable savingsBalance indicating the amount the saver currently has on deposit.

Provide method calculateMonthlyInterest to calculate the monthly interest by multiplying the savingsBalance by annualInterestRate divided by 12—this interest should be added to savingsBalance. Provide a static method modifyInterestRate that sets the annualInterestRate to a new value. Write a program to test class SavingsAccount. Instantiate two savingsAccount objects, saver1 and saver2, with balances of $2000.00 and $3000.00, respectively. Set annualInterestRate to 4%, then calculate the monthly interest for each of 12 months and print the new balances for both savers. Next, set the annualInterestRate to 5%, calculate the next month’s interest and print the new balances for both savers.

8.7 (Enhancing Class Time2) Modify class Time2 of Fig. 8.5 to include a tick method that increments the time stored in a Time2 object by one second. Provide method incrementMinute to increment the minute by one and method incrementHour to increment the hour by one. Write a

program that tests the tick method, the incrementMinute method and the incrementHour method to ensure that they work correctly. Be sure to test the following cases:

a) incrementing into the next minute,

b) incrementing into the next hour and

c) incrementing into the next day (i.e., 11:59:59 PM to 12:00:00 AM).

8.8 (Enhancing Class Date) Modify class Date of Fig. 8.7 to perform error checking on the initializer values for instance variables month, day and year (currently it validates only the month and day). Provide a method nextDay to increment the day by one. Write a program that tests method nextDay in a loop that prints the date during each iteration to illustrate that the method works correctly.

Test the following cases:

a) incrementing into the next month and

b) incrementing into the next year.

8.9 Rewrite the code in Fig. 8.14 to use a separate import declaration for each static member of class Math that’s used in the example.

8.10 Write an enum type TrafficLight, whose constants (RED, GREEN, YELLOW) take one parameter—the duration of the light. Write a program to test the TrafficLight enum so that it displays the enum constants and their durations.

8.11 (Complex Numbers) Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have the form

realPart + imaginaryPart * I, where i is sqrt(-1)

Write a program to test your class. Use floating-point variables to represent the private data of the class. Provide a constructor that enables an object of this class to be initialized when it’s declared.

Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods that perform the following operations:

a) Add two Complex numbers: The real parts are added together and the imaginary parts are added together.

b) Subtract two Complex numbers: The real part of the right operand is subtracted from the real part of the left operand, and the imaginary part of the right operand is subtracted from the imaginary part of the left operand.

c) Print Complex numbers in the form (realPart, imaginaryPart).

8.12 (Date and Time Class) Create class DateAndTime that combines the modified Time2 class of Exercise 8.7 and the modified Date class of Exercise 8.8. Modify method incrementHour to call method nextDay if the time is incremented into the next day. Modify methods toString and toUniversalString to output the date in addition to the time. Write a program to test the new class DateAndTime.

Specifically, test incrementing the time to the next day.

8.13 (Set of Integers) Create class IntegerSet. Each IntegerSet object can hold integers in the range 0–100. The set is represented by an array of booleans. Array element a[i] is true if integer i is in the set. Array element a[j] is false if integer j is not in the set. The no-argument constructor initializes the array to the “empty set” (i.e., all false values). Provide the following methods: The static method union creates a set that’s the set-theoretic union of two existing sets (i.e., an element of the new set’s array is set to true if that element is true in either or both of the existing sets—otherwise, the new set’s element is set to false). The static method intersection creates a set which is the set-theoretic intersection of two existing sets (i.e., an element of the new set’s array is set to false if that element is false in either or both of the existing sets—otherwise, the new set’s element is set to true). Method insertElement inserts a new integer k into a set (by setting a[k] to true). Method deleteElement deletes integer m (by setting a[m] to false). Method toString returns a String containing a set as a list of numbers separated by spaces. Include only those elements that are present in the set. Use --- to represent an empty set. Method isEqualTo determines whether two sets are equal. Write a program to test class IntegerSet. Instantiate several IntegerSet objects. Test that all your methods work properly.  

8.14 (Date Class) Create class Date with the following capabilities:

a) Output the date in multiple formats, such as

MM/DD/YYYY

June 14, 1992

DDD YYYY

b) Use overloaded constructors to create Date objects initialized with dates of the formats in part (a). In the first case the constructor should receive three integer values. In the second case it should receive a String and two integer values. In the third case it should receive two integer values, the first of which represents the day number in the year. [Hint: To convert the String representation of the month to a numeric value, compare Strings using the equals method. For example, if s1 and s2 are Strings, the method call s1.equals(s2) returns true if the Strings are identical and otherwise returns false.]

8.15 (Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private instance variables of the class—the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it’s declared. The constructor should store the fraction in reduced form. The fraction 2/4 is equivalent to 1/2 and would be stored in the object as 1 in the numerator and 2 in the denominator. Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods that perform each of the following operations:

a) Add two Rational numbers: The result of the addition should be stored in reduced form. Implement this as a static method.

b) Subtract two Rational numbers: The result of the subtraction should be stored in reduced form. Implement this as a static method.

c) Multiply two Rational numbers: The result of the multiplication should be stored in reduced form. Implement this as a static method.

d) Divide two Rational numbers: The result of the division should be stored in reduced form. Implement this as a static method.

e) Return a String representation of a Rational number in the form a/b, where a is the numerator and b is the denominator.

f) Return a String representation of a Rational number in floating-point format. (Consider providing formatting capabilities that enable the user of the class to specify the number of digits of precision to the right of the decimal point.)

8.16 (Huge Integer Class) Create a class HugeInteger which uses a 40-element array of digits to store integers as large as 40 digits each. Provide methods parse, toString, add and subtract. Method parse should receive a String, extract each digit using method charAt and place the integer equivalent of each digit into the integer array. For comparing HugeInteger objects, provide the following methods: isEqualTo, isNotEqualTo, isGreaterThan, isLessThan, isGreaterThanOrEqualTo and isLessThanOrEqualTo. Each of these is a predicate method that returns true if the relationship holds between the two HugeInteger objects and returns false if the relationship does not hold. Provide a predicate method isZero. If you feel ambitious, also provide methods multiply, divide and remainder. [Note: Primitive boolean values can be output as the word “true” or the word “false” with format specifier %b.]

8.17 (Tic-Tac-Toe) Create a class TicTacToe that will enable you to write a program to play Tic- Tac-Toe. The class contains a private 3-by-3 two-dimensional array. Use an enum type to represent the value in each cell of the array. The enum’s constants should be named X, O and EMPTY (for a position that does not contain an X or an O). The constructor should initialize the board elements to EMPTY. Allow two human players. Wherever the first player moves, place an X in the specified square, and place an O wherever the second player moves. Each move must be to an empty square. After each move, determine whether the game has been won and whether it’s a draw. If you feel ambitious, modify your program so that the computer makes the moves for one of the players. Also, allow the player to specify whether he or she wants to go first or second. If you feel exceptionally ambitious, develop a program that will play three-dimensional Tic-Tac-Toe on a 4-by-4-by-4 board [Note: This is an extremely challenging project!].

8.18 (Account Class with BigDecimal balance) Rewrite the Account class of Section 3.5 to store the balance as a BigDecimal object and to perform all calculations using BigDecimals.

Making a Difference

8.19 (Project: Emergency Response Class)

The North American emergency response service, 9-1-1, connects callers to a local Public Service Answering Point (PSAP). Traditionally, the PSAP would ask the caller for identification information—including the caller’s address, phone number and the nature of the emergency, then dispatch the appropriate emergency responders (such as the police, an ambulance or the fire department). Enhanced 9-1-1 (or E9-1-1) uses computers and databases to determine the caller’s physical address, directs the call to the nearest PSAP, and displays the caller’s phone number and address to the call taker. Wireless Enhanced 9-1-1 provides call takers with identification information for wireless calls. Rolled out in two phases, the first phase required carriers to provide the wireless phone number and the location of the cell site or base station transmitting the call. The second phase required carriers to provide the location of the caller (using technologies such as GPS). To learn more about 9-1-1, visit http://www.fcc.gov/pshs/services/911-services/Welcome.html and http://people.howstuffworks.com/9-1-1.htm. An important part of creating a class is determining the class’s attributes (instance variables). For this class design exercise, research 9-1-1 services on the Internet. Then, design a class called Emergency that might be used in an object-oriented 9-1-1 emergency response system. List the attributes that an object of this class might use to represent the emergency. For example, the class might include information on who reported the emergency (including their phone number), the location of the emergency, the time of the report, the nature of the emergency, the type of response and the status of the response. The class attributes should completely describe the nature of the problem and what’s happening to resolve that problem.

你可能感兴趣的:(Java编程(Java,Programming))