• 沒有找到結果。

[1] http://www.unicode.org/ The web site of the Unicode consortium. It contains character tables that show the Unicode values of characters from many scripts.

java.io.BufferedReader readLine

java.io.InputStreamReader java.lang.Double

parseDouble toString java.lang.Integer parseInt toString MAX_VALUE MIN_VALUE java.lang.Math E

PI abs acos asin atan atan2 ceil cos exp floor log max min pow round sin sqrt tan toDegrees toRadians java.lang.String length

substring toLowerCase toUpperCase java.lang.System exit

in

java.math.BigDecimal add

divide multiply subtract

Classes, Objects, and Methods Introduced in

This Chapter

java.math.BigInteger add

divide multiply subtract

java.text.NumberFormat format

getCurrencyInstance getNumberInstance

setMaximumFractionDigits setMinimumFractionDigits javax.swing.JOptionPane showInputDialog

Exercise R3.1. Write the following mathematical expressions in Java.

Exercise R3.2. Write the following Java expressions in mathematical notation.

dm = m * ((Math.sqrt(1 + v / c) / Math.sqrt(1 - v / c)) - 1);

volume = Math.PI * r * r * h;

volume = 4 * Math.PI * Math.pow(r, 3) / 3;

p = Math.atan2(z, Math.sqrt(x * x + y * y));

Exercise R3.3. What is wrong with this version of the quadratic formula?

x1 = (-b - Math.sqrt(b * b - 4 * a * c)) / 2 * a;

x2 = (-b + Math.sqrt(b * b - 4 * a * c)) / 2 * a;

Exercise R3.4. Give an example of integer overflow. Would the same example work cor-rectly if you used floating-point? Give an example of a floating-point roundoff error.

Would the same example work correctly if you used integers? For this exercise, you should assume that the values are represented in a sufficiently small unit, such as cents instead of dollars, so that the values don’t have a fractional part.

Exercise R3.5. Write a test program that executes the following code:

Purse myPurse = new Purse();

myPurse.addNickels(3);

Review Exercises

s s0 v0t 1 2---gt2

 



G 42 a

P2(m1m2)

---

FV PV 1 INT

---100

  

 YRS



c  a2b22abcos

myPurse.addDimes(2);

myPurse.addQuarters(1);

System.out.println(myPurse.getTotal());

The program prints the total as 0.6000000000000001. Explain why. Give a recommen-dation to improve the program so that users will not be confused.

Exercise R3.6. Let n be an integer and x a floating-point number. Explain the difference between

n = (int)x;

and

n = (int)Math.round(x);

Exercise R3.7. Let n be an integer and x a floating-point number. Explain the difference between

n = (int)(x + 0.5);

and

n = (int)Math.round(x);

For what values of x do they give the same result? For what values of x do they give dif-ferent results?

Exercise R3.8. Explain the differences between 2, 2.0, '2', "2", and "2.0". Exercise R3.9. Explain what each of the following two program segments computes:

x = 2;

y = x + x;

and

s = "2";

t = s + s;

Exercise R3.10. Uninitialized variables can be a serious problem. Should you always initial-ize every variable with zero? Explain the advantages and disadvantages of such a strategy.

Exercise R3.11. True or false? (x is an int and s is a String)

 Integer.parseInt("" + x) is the same as x

 "" + Integer.parseInt(s) is the same as s

 s.substring(0, s.length()) is the same as s

Exercise R3.12. How do you get the first character of a string? The last character? How do you remove the first character? The last character?

Exercise R3.13. How do you get the last digit of an integer? The first digit? That is, if n is 23456, how do you find out that the first digit is 2 and the last digit is 6? Do not con-vert the number to a string. Hint: %, Math.log.

Exercise R3.14. This chapter contains several recommendations regarding variables and con-stants that make programs easier to read and maintain. Summarize these recommendations.

Exercise R3.15. What is a final variable? Can you define a final variable without supplying its value? (Try it out.)

Exercise R3.16. What are the values of the following expressions? In each line, assume that double x = 2.5;

double y = -1.5;

int m = 18;

int n = 4;

String s = "Hello";

String t = "World";

 x + n * y - (x + n) * y

 m / n + m % n

 5 * x - n / 5

 Math.sqrt(Math.sqrt(n))

 (int)Math.round(x)

 (int)Math.round(x) + (int)Math.round(y)

 s + t

 s + n

 1 - (1 - (1 - (1 - (1 - n))))

 s.substring(1, 3)

 s.length() + t.length()

Exercise R3.17. Explain the similarities and differences between copying numbers and copying object references.

Exercise R3.18. What are the values of a, b, c, and d after these statements?

double a = 1;

double b = a;

a++;

Purse p = new Purse();

Purse q = p;

p.addNickels(5);

double c = p.getTotal();

double d = q.getTotal();

Exercise R3.19. When you copy a BankAccount reference, the original and the copy share the same object. That can be significant because you can modify the state of the object through either of the references. Explain why this is not a problem for String references.

Exercise P3.1. Enhance the Purse class by adding methods addPennies and addDollars.

Programming Exercises

Exercise P3.2. Add methods getDollars and getCents to the Purse class. The get-Dollars method should return the number of whole dollars in the purse, as an integer.

The getCents method should return the number of cents, as an integer. For example, if the total value of the coins in the purse is $2.14, getDollars returns 2 and getCents returns 14.

Exercise P3.3. Write a program that prints the values 1

10 100 1000 10000 100000 1000000 10000000 100000000 1000000000 10000000000 100000000000 Implement a class

public class PowerGenerator {

/**

Constructs a power generator.

@param aFactor the number that will be multiplied by itself */

public PowerGenerator(int aFactor) { . . } /**

Computes the next power.

*/

public double nextPower() { . . . } . . .

}

Then supply a test class PowerGeneratorTest that calls System.out.println(

myGenerator.nextPower()) twelve times.

Exercise P3.4. Write a program that prompts the user for two integers and then prints

 The sum

 The difference

 The product

 The average

 The distance (absolute value of the difference)

 The maximum (the larger of the two)

 The minimum (the smaller of the two) Implement a class

public class Pair {

/**

Constructs a pair.

@param aFirst the first value of the pair @param aSecond the second value of the pair */

public Pair(double aFirst, double aSecond) { . . . } /**

Computes the sum of the values of this pair.

@return the sum of the first and second values */

public double getSum() { . . . } . . .

}

Then implement a class PairTest that reads in two numbers (using either a JOption-Pane or a BufferedReader), constructs a Pair object, invokes its methods, and prints the results.

Exercise P3.5. Write a program that reads in four integers and prints their sum and aver-age. Define a class DataSet with methods

void addValue(int x) int getSum()

double getAverage()

Hint: Keep track of the sum and the count of the values. Then write a test program DataSetTest that reads four numbers and calls addValue four times.

Exercise P3.6. Write a program that reads in four integers and prints the largest and smallest value that the user entered. Use a class DataSet with methods

 void addValue(int x)

 int getLargest()

 int getSmallest()

Keep track of the smallest and largest value that you’ve seen so far. Then use the Math.min and Math.max methods to update it in the addValue method. What should you use as initial values? Hint: Integer.MIN_VALUE, Integer.MAX_VALUE.

Write a test program DataSetTest that reads four numbers and calls addValue four times.

Exercise P3.7. Write a program that prompts the user for a measurement in meters and then converts it into miles, feet, and inches. Use a class

public class Converter {

/**

Constructs a converter that can convert between two units.

@param aConversionFactor the factor with which to multiply to convert to the target unit

*/

public Converter(double aConversionFactor) { . . . } /**

Converts from a source measurement to a target measurement.

@param fromMeasurement the measurement @return the input value converted to the target unit */

public double convertTo(double fromMeasurement) { . . . } }

Then construct three instances, such as

final double MILE_TO_KM = 1.609; // from Appendix A7

Converter metersToMiles = new Converter(1000 * MILE_TO_KM);

Exercise P3.8. Write a program that prompts the user for a radius and then prints

 The area and circumference of the circle with that radius

 The volume and surface area of the sphere with that radius Define classes Circle and Sphere.

Exercise P3.9. Implement a class SodaCan whose constructor receives the height and diameter of the soda can. Supply methods getVolume and getSurfaceArea. Supply a SodaCanTest class that tests your class.

Exercise P3.10. Write a program that asks the user for the length of the sides of a square.

Then print

 The area and perimeter of the square

 The length of the diagonal (use the Pythagorean theorem) Define a class Square.

Exercise P3.11. Giving change. Implement a program that directs a cashier how to give change. The program has two inputs: the amount due and the amount received from the customer. Compute the difference, and compute the dollars, quarters, dimes, nickels, and pennies that the customer should receive in return.

First transform the difference into an integer balance, denominated in pennies. Then compute the whole dollar amount. Subtract it from the balance. Compute the number of quarters needed. Repeat for dimes and nickels. Display the remaining pennies.

Define a class Cashier with methods

 setAmountDue

 receive

 returnDollars

 returnQuarters

 returnDimes

 returnNickels

 returnPennies For example,

Cashier harry = new Cashier();

harry.setAmountDue(9.37);

harry.receive(10);

double quarters = harry.returnQuarters(); // returns 2 double dimes = harry.returnDimes(); // returns 1 double nickels = harry.returnNickels(); // returns 0 double pennies = harry.returnPennies(); // returns 3

Exercise P3.12. Write a program that reads in an integer and breaks it into a sequence of individual digits in reverse order. For example, the input 16384 is displayed as

4 8 3 6 1

You may assume that the input has no more than five digits and is not negative.

Define a class DigitExtractor: public class DigitExtractor {

/**

Constructs a digit extractor that gets the digits of an integer in reverse order.

@param anInteger the integer to break up into digits */

public DigitExtractor(int anInteger) { . . . } /**

Returns the next digit to be extracted.

@return the next digit */

public double nextDigit() { . . . } }

Then call System.out.println(myExtractor.nextDigit()) five times.

Exercise P3.13. Implement a class QuadraticEquation whose constructor receives the coefficients a, b, c of the quadratic equation ax2 + bx + c = 0. Supply methods getSolution1 and getSolution2 that get the solutions, using the quadratic formula.

Write a test class QuadraticEquationTest that prompts the user for the values of a, b, and c, constructs a QuadraticEquation object, and prints the two solutions.

Exercise P3.14. Write a program that reads two times in military format (0900, 1730) and prints the number of hours and minutes between the two times. Here is a sample run. User input is in color.

Please enter the first time: 0900 Please enter the second time: 1730 8 hours 30 minutes

Extra credit if you can deal with the case where the first time is later than the second time:

Please enter the first time: 1730 Please enter the second time: 0900 15 hours 30 minutes

Implement a class TimeInterval whose constructor takes two military times. The class should have two methods getHours and getMinutes.

Exercise P3.15. Writing large letters. A large letter H can be produced like this:

* *

* *

*****

* *

* *

Define a class LetterH with a method String getLetter()

{

return "* *\n* *\n*****\n* *\n* *\n";

}

Do the same for the letters E, L, and O. Then write the message H

E L L O

in large letters.

Exercise P3.16. Write a program that transforms numbers 1, 2, 3, ... , 12 into the corre-sponding month names January, February, March, ... , December. Hint: Make a very long string "January February March. . .", in which you add spaces such that each month name has the same length. Then use substring to extract the month you want.

Implement a class Month whose constructor parameter is the month number and whose getName method returns the month name.

Exercise P3.17. Write a program to compute the date of Easter Sunday. Easter Sunday is the first Sunday after the first full moon of Spring. Use this algorithm, invented by the mathematician Carl Friedrich Gauss in 1800:

1. Let y be the year (such as 1800 or 2001)

2. Divide y by 19 and call the remainder a. Ignore the quotient.

3. Divide y by 100 to get a quotient b and a remainder c 4. Divide b by 4 to get a quotient d and a remainder e

5. Divide 8 * b + 13 by 25 to get a quotient g. Ignore the remainder.

6. Divide 19 * a + b - d - g + 15 by 30 to get a remainder h. Ignore the quotient.

7. Divide c by 4 to get a quotient j and a remainder k

8. Divide a + 11 * h by 319 to get a quotient m. Ignore the remainder.

9. Divide 2 * e + 2 * j - k - h + m + 32 by 7 to get a remainder r. Ignore the quotient.

10. Divide h - m + r + 90 by 25 to get a quotient n. Ignore the remainder.

11. Divide h - m + r + n + 19 by 32 to get a remainder p. Ignore the quotient.

Then Easter falls on day p of month n. For example, if y is 2001:

a = 6 b = 20 c = 1

d = 5, e = 0 g = 6

h = 18 j = 0, k = 1 m = 0

r = 6 n = 4 p = 15

Therefore, in 2001, Easter Sunday fell on April 15. Write a class Year with methods getEasterSundayMonth and getEasterSundayDay.

相關文件