Wrap-Up

Answers to Self Review Exercises

6.1

a) method call. b) local variable. c) return. d) void. e) top. f) last-in, first-out (LIFO). g) return; or return expression; or encountering the closing right brace of a method. h) Random. i) activation record, stack frame. j) stack overflow. k) scope. l) overloading. m) method call.

6.2

a) class body. b) block that defines method rollDice's body. c) class body. d) class body. e) block that defines method play's body.

6.3

The following solution demonstrates the Math class methods in Fig. 6.2:

 1 // Exercise 6.3: MathTest.java
 2 // Testing the Math class methods.
 3
 4 public class MathTest
 5 {
 6 public static void main( String args[] )
 7 {
 8 System.out.printf( "Math.abs( 23.7 ) = %f
", Math.abs( 23.7 ) );
 9 System.out.printf( "Math.abs( 0.0 ) = %f
", Math.abs( 0.0 ) );
10 System.out.printf( "Math.abs( -23.7 ) = %f
", Math.abs( -23.7 ) );
11 System.out.printf( "Math.ceil( 9.2 ) = %f
", Math.ceil( 9.2 ) );
12 System.out.printf( "Math.ceil( -9.8 ) = %f
", Math.ceil( -9.8 ) );
13 System.out.printf( "Math.cos( 0.0 ) = %f
", Math.cos( 0.0 ) );
14 System.out.printf( "Math.exp( 1.0 ) = %f
", Math.exp( 1.0 ) );
15 System.out.printf( "Math.exp( 2.0 ) = %f
", Math.exp( 2.0 ) );
16 System.out.printf( "Math.floor( 9.2 ) = %f
", Math.floor( 9.2 ) );
17 System.out.printf( "Math.floor( -9.8 ) = %f
",
18 Math.floor( -9.8 ) );
19 System.out.printf( "Math.log( Math.E ) = %f
",
20 Math.log( Math.E ) );
21 System.out.printf( "Math.log( Math.E * Math.E ) = %f
",
22 Math.log( Math.E * Math.E ) );
23 System.out.printf( "Math.max( 2.3, 12.7 ) = %f
",
24 Math.max( 2.3, 12.7 ) );
25 System.out.printf( "Math.max( -2.3, -12.7 ) = %f
",
26 Math.max( -2.3, -12.7 ) );
27 System.out.printf( "Math.min( 2.3, 12.7 ) = %f
",
28 Math.min( 2.3, 12.7 ) );
29 System.out.printf( "Math.min( -2.3, -12.7 ) = %f
",
30 Math.min( -2.3, -12.7 ) );
31 System.out.printf( "Math.pow( 2.0, 7.0 ) = %f
",
32 Math.pow( 2.0, 7.0 ) );
33 System.out.printf( "Math.pow( 9.0, 0.5 ) = %f
",
34 Math.pow( 9.0, 0.5 ) );
35 System.out.printf( "Math.sin( 0.0 ) = %f
", Math.sin( 0.0 ) );
36 System.out.printf( "Math.sqrt( 900.0 ) = %f
",
37 Math.sqrt( 900.0 ) );
38 System.out.printf( "Math.sqrt( 9.0 ) = %f
", Math.sqrt( 9.0 ) );
39 System.out.printf( "Math.tan( 0.0 ) = %f
", Math.tan( 0.0 ) );
40 } // end main
41 } // end class MathTest
 
Math.abs( 23.7 ) = 23.700000
Math.abs( 0.0 ) = 0.000000
Math.abs( -23.7 ) = 23.700000
Math.ceil( 9.2 ) = 10.000000
Math.ceil( -9.8 ) = -9.000000
Math.cos( 0.0 ) = 1.000000
Math.exp( 1.0 ) = 2.718282
Math.exp( 2.0 ) = 7.389056
Math.floor( 9.2 ) = 9.000000
Math.floor( -9.8 ) = -10.000000
Math.log( Math.E ) = 1.000000
Math.log( Math.E * Math.E ) = 2.000000
Math.max( 2.3, 12.7 ) = 12.700000
Math.max( -2.3, -12.7 ) = -2.300000
Math.min( 2.3, 12.7 ) = 2.300000
Math.min( -2.3, -12.7 ) = -12.700000
Math.pow( 2.0, 7.0 ) = 128.000000
Math.pow( 9.0, 0.5 ) = 3.000000
Math.sin( 0.0 ) = 0.000000
Math.sqrt( 900.0 ) = 30.000000
Math.sqrt( 9.0 ) = 3.000000
Math.tan( 0.0 ) = 0.000000
 
6.4
  1. double hypotenuse( double side1, double side2 )
  2. int smallest( int x, int y, int z )
  3. void instructions()
  4. float intToFloat( int number )
6.5
  1. Error: Method h is declared within method g.

    Correction: Move the declaration of h outside the declaration of g.

  2. Error: The method is supposed to return an integer, but does not.

    Correction: Delete the variable result, and place the statement

     return x + y;
    

    in the method, or add the following statement at the end of the method body:

     return result;
    
  3. Error: The semicolon after the right parenthesis of the parameter list is incorrect, and the parameter a should not be redeclared in the method.

    Correction: Delete the semicolon after the right parenthesis of the parameter list, and delete the declaration float a;.

  4. Error: The method returns a value when it is not supposed to.

    Correction: Change the return type from void to int.

6.6

The following solution calculates the volume of a sphere, using the radius entered by the user:

 1 // Exercise 6.6: Sphere.java
 2 // Calculate the volume of a sphere.
 3 import java.util.Scanner;
 4
 5 public class Sphere
 6 {
 7 // obtain radius from user and display volume of sphere
 8 public void determineSphereVolume()
 9 {
10 Scanner input = new Scanner( System.in ); 11 12 System.out.print( "Enter radius of sphere: " ); 13 double radius = input.nextDouble(); 14 15 System.out.printf( "Volume is %f ", sphereVolume( radius ) ); 16 } // end method determineSphereVolume 17 18 // calculate and return sphere volume 19 public double sphereVolume( double radius ) 20 { 21 double volume = ( 4.0 / 3.0 ) * Math.PI * Math.pow( radius, 3 ); 22 return volume; 23 } // end method sphereVolume 24 } // end class Sphere  
 1 // Exercise 6.6: SphereTest.java
 2 // Calculate the volume of a sphere.
 3
 4 public class SphereTest
 5 {
 6 // application starting point
 7 public static void main( String args[] )
 8 {
 9 Sphere mySphere = new Sphere();
10 mySphere.determineSphereVolume();
11 } // end main
12 } // end class SphereTest
 
Enter radius of sphere: 4
Volume is 268.082573
 


Exercises

6.7

What is the value of x after each of the following statements is executed?

  1. x = Math.abs( 7.5 );
  2. x = Math.floor( 7.5 );
  3. x = Math.abs( 0.0 );
  4. x = Math.ceil( 0.0 );
  5. x = Math.abs( -6.4 );
  6. x = Math.ceil( -6.4 );
  7. x = Math.ceil(-Math.abs( -8 + Math.floor( -5.5 ) ) );
6.8

A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. Assume that no car parks for longer than 24 hours at a time. Write an application that calculates and displays the parking charges for each customer who parked in the garage yesterday. You should enter the hours parked for each customer. The program should display the charge for the current customer and should calculate and display the running total of yesterday's receipts. The program should use the method calculateCharges to determine the charge for each customer.

 
6.9

An application of method Math.floor is rounding a value to the nearest integer. The statement

 y = Math.floor( x + 0.5 );
 

will round the number x to the nearest integer and assign the result to y. Write an application that reads double values and uses the preceding statement to round each of the numbers to the nearest integer. For each number processed, display both the original number and the rounded number.

6.10

Math.floor may be used to round a number to a specific decimal place. The statement

 y = Math.floor( x * 10 + 0.5 ) / 10;
 

rounds x to the tenths position (i.e., the first position to the right of the decimal point). The statement

 y = Math.floor( x * 100 + 0.5 ) / 100;
 

rounds x to the hundredths position (i.e., the second position to the right of the decimal point).

Write an application that defines four methods for rounding a number x in various ways:

  1. roundToInteger( number )
  2. roundToTenths( number )
  3. roundToHundredths( number )
  4. roundToThousandths( number )

For each value read, your program should display the original value, the number rounded to the nearest integer, the number rounded to the nearest tenth, the number rounded to the nearest hundredth and the number rounded to the nearest thousandth.

6.11

Answer each of the following questions:

  1. What does it mean to choose numbers "at random?"
  2. Why is the Math.random method useful for simulating games of chance?
  3. Why is it often necessary to scale or shift the values produced by a Random object?
  4. Why is computerized simulation of real-world situations a useful technique?
6.12

Write statements that assign random integers to the variable n in the following ranges:

  1. 1 < n < 2
  2. 1 < n < 100
  3. 0 < n < 9
  4. 1000 < n < 1112
  5. 1 < n < 1
  6. 3 < n < 11
6.13

For each of the following sets of integers, write a single statement that will display a number at random from the set:

  1. 2, 4, 6, 8, 10.
  2. 3, 5, 7, 9, 11.
  3. 6, 10, 14, 18, 22.
6.14

Write a method integerPower( base, exponent ) that returns the value of


      baseexponent

For example, integerPower( 3, 4 ) calculates 34 (or 3 * 3 * 3 * 3 ). Assume that exponent is a positive, nonzero integer and that base is an integer. Method integerPower should use a for or while loop to control the calculation. Do not use any math-library methods. Incorporate this method into an application that reads integer values for base and exponent and performs the calculation with the integerPower method.

6.15

Define a method hypotenuse that calculates the length of the hypotenuse of a right triangle when the lengths of the other two sides are given. (Use the sample data in Fig. 6.26.) The method should take two arguments of type double and return the hypotenuse as a double. Incorporate this method into an application that reads values for side1 and side2 and performs the calculation with the hypotenuse method. Determine the length of the hypotenuse for each of the triangles in Fig. 6.26.

Figure 6.26. Values for the sides of triangles in Exercise 6.15.

Triangle

Side 1

Side 2

1

3.0

4.0

2

5.0

12.0

3

8.0

15.0

6.16

Write a method multiple that determines, for a pair of integers, whether the second integer is a multiple of the first. The method should take two integer arguments and return TRue if the second is a multiple of the first and false otherwise. Incorporate this method into an application that inputs a series of pairs of integers (one pair at a time) and determines whether the second value in each pair is a multiple of the first.

6.17

Write a method isEven that uses the remainder operator (%) to determine whether an integer is even. The method should take an integer argument and return true if the integer is even and false otherwise. Incorporate this method into an application that inputs a sequence of integers (one at a time) and determines whether each is even or odd.

6.18

Write a method squareOfAsterisks that displays a solid square (the same number of rows and columns) of asterisks whose side is specified in integer parameter side. For example, if side is 4, the method should display

 ****
 ****
 ****
 ****
 

Incorporate this method into an application that reads an integer value for side from the user and outputs the asterisks with the squareOfAsterisks method.

6.19

Modify the method created in Exercise 6.18 to form the square out of whatever character is contained in character parameter fillCharacter. Thus, if side is 5 and fillCharacter is "#", the method should display

 #####
 #####
 #####
 #####
 #####
6.20

Write an application that prompts the user for the radius of a circle and uses a method called circleArea to calculate the area of the circle.

6.21

Write program segments that accomplish each of the following tasks:

  1. Calculate the integer part of the quotient when integer a is divided by integer b.
  2. Calculate the integer remainder when integer a is divided by integer b.
  3. Use the program pieces developed in parts (a) and (b) to write a method displayDigits that receives an integer between 1 and 99999 and displays it as a sequence of digits, separating each pair of digits by two spaces. For example, the integer 4562 should appear as

     4 5 6 2
    
  4. Incorporate the method developed in part (c) into an application that inputs an integer and calls displayDigits by passing the method the integer entered. Display the results.
6.22

Implement the following integer methods:

  1. Method celsius returns the Celsius equivalent of a Fahrenheit temperature, using the calculation

     C = 5.0 / 9.0 * ( F - 32 );
    
  2. Method fahrenheit returns the Fahrenheit equivalent of a Celsius temperature, using the calculation

     F = 9.0 / 5.0 * C + 32;
    
  3. Use the methods from parts (a) and (b) to write an application that enables the user either to enter a Fahrenheit temperature and display the Celsius equivalent or to enter a Celsius temperature and display the Fahrenheit equivalent.
6.23

Write a method minimum3 that returns the smallest of three floating-point numbers. Use the Math.min method to implement minimum3. Incorporate the method into an application that reads three values from the user, determines the smallest value and displays the result.

6.24

An integer number is said to be a perfect number if its factors, including 1 (but not the number itself), sum to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3. Write a method perfect that determines whether parameter number is a perfect number. Use this method in an application that determines and displays all the perfect numbers between 1 and 1000. Display the factors of each perfect number to confirm that the number is indeed perfect. Challenge the computing power of your computer by testing numbers much larger than 1000. Display the results.

6.25

An integer is said to be prime if it is divisible by only 1 and itself. For example, 2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not.

  1. Write a method that determines whether a number is prime.
  2. Use this method in an application that determines and displays all the prime numbers less than 10,000. How many numbers up to 10,000 do you have to test to ensure that you have found all the primes?
  3. Initially, you might think that n/2 is the upper limit for which you must test to see whether a number is prime, but you need only go as high as the square root of n. Why? Rewrite the program, and run it both ways. Estimate the performance improvement.
6.26

Write a method that takes an integer value and returns the number with its digits reversed. For example, given the number 7631, the method should return 1367. Incorporate the method into an application that reads a value from the user and displays the result.

6.27

The greatest common divisor (GCD) of two integers is the largest integer that evenly divides each of the two numbers. Write a method gcd that returns the greatest common divisor of two integers. Incorporate the method into an application that reads two values from the user and displays the result.

6.28

Write a method qualityPoints that inputs a student's average and returns 4 if the student's average is 90100, 3 if the average is 8089, 2 if the average is 7079, 1 if the average is 6069 and 0 if the average is lower than 60. Incorporate the method into an application that reads a value from the user and displays the result.

6.29

Write an application that simulates coin tossing. Let the program toss a coin each time the user chooses the "Toss Coin" menu option. Count the number of times each side of the coin appears. Display the results. The program should call a separate method flip that takes no arguments and returns false for tails and TRue for heads. [Note : If the program realistically simulates coin tossing, each side of the coin should appear approximately half the time.]

 
6.30

Computers are playing an increasing role in education. Write a program that will help an elementary school student learn multiplication. Use a Random object to produce two positive one-digit integers. The program should then prompt the user with a question, such as

 How much is 6 times 7?
 

The student then inputs the answer. Next, the program checks the student's answer. If it is correct, display the message "Very good!" and ask another multiplication question. If the answer is wrong, display the message "No. Please try again." and let the student try the same question repeatedly until the student finally gets it right. A separate method should be used to generate each new question. This method should be called once when the application begins execution and each time the user answers the question correctly.

6.31

The use of computers in education is referred to as computer-assisted instruction (CAI). One problem that develops in CAI environments is student fatigue. This problem can be eliminated by varying the computer's responses to hold the student's attention. Modify the program of Exercise 6.30 so that the various comments are displayed for each correct answer and each incorrect answer as follows:

Responses to a correct answer:

 Very good!
 Excellent!
 Nice work!
 Keep up the good work!
 

Responses to an incorrect answer:

 No. Please try again.
 Wrong. Try once more.
 Don't give up!
 No. Keep trying.
 

Use random-number generation to choose a number from 1 to 4 that will be used to select an appropriate response to each answer. Use a switch statement to issue the responses.

6.32

More sophisticated computer-assisted instruction systems monitor the student's performance over a period of time. The decision to begin a new topic is often based on the student's success with previous topics. Modify the program of Exercise 6.31 to count the number of correct and incorrect responses typed by the student. After the student types 10 answers, your program should calculate the percentage of correct responses. If the percentage is lower than 75%, display Please ask your instructor for extra help and reset the program so another student can try it.

6.33

Write an application that plays "guess the number" as follows: Your program chooses the number to be guessed by selecting a random integer in the range 1 to 1000. The application displays the prompt Guess a number between 1 and 1000. The player inputs a first guess. If the player's guess is incorrect, your program should display Too high. Try again. or Too low. Try again. to help the player "zero in" on the correct answer. The program should prompt the user for the next guess. When the user enters the correct answer, display Congratulations. You guessed the number!, and allow the user to choose whether to play again. [Note : The guessing technique employed in this problem is similar to a binary search, which is discussed in Chapter 16, Searching and Sorting.]

6.34

Modify the program of Exercise 6.33 to count the number of guesses the player makes. If the number is 10 or fewer, display Either you know the secret or you got lucky! If the player guesses the number in 10 tries, display Aha! You know the secret! If the player makes more than 10 guesses, display You should be able to do better! Why should it take no more than 10 guesses? Well, with each "good guess," the player should be able to eliminate half of the numbers. Now show why any number from 1 to 1000 can be guessed in 10 or fewer tries.

 
6.35

Exercise 6.30 through Exercise 6.32 developed a computer-assisted instruction program to teach an elementary school student multiplication. Perform the following enhancements:

  1. Modify the program to allow the user to enter a school grade-level capability. A grade level of 1 means that the program should use only single-digit numbers in the problems, a grade level of 2 means that the program should use numbers as large as two digits, and so on.
  2. Modify the program to allow the user to pick the type of arithmetic problems he or she wishes to study. An option of 1 means addition problems only, 2 means subtraction problems only, 3 means multiplication problems only, 4 means division problems only and 5 means a random mixture of problems of all these types.
6.36

Write method distance to calculate the distance between two points (x1, y1) and (x2, y2). All numbers and return values should be of type double. Incorporate this method into an application that enables the user to enter the coordinates of the points.

6.37

Modify the craps program of Fig. 6.9 to allow wagering. Initialize variable bankBalance to 1000 dollars. Prompt the player to enter a wager. Check that wager is less than or equal to bankBalance, and if it is not, have the user reenter wager until a valid wager is entered. After a correct wager is entered, run one game of craps. If the player wins, increase bankBalance by wager and display the new bankBalance. If the player loses, decrease bankBalance by wager, display the new bankBalance, check whether bankBalance has become zero and, if so, display the message "Sorry. You busted!" As the game progresses, display various messages to create some "chatter," such as "Oh, you're going for broke, huh?" or "Aw c'mon, take a chance!" or "You're up big. Now's the time to cash in your chips!". Implement the "chatter" as a separate method that randomly chooses the string to display.

6.38

Write an application that displays a table of the binary, octal, and hexadecimal equivalents of the decimal numbers in the range 1 through 256. If you are not familiar with these number systems, read Appendix E first.

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover





Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615
Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net