Included below are short-answer and programming exercises. Answers are provided for those exercises whose exercise number is a hyperlink. Because college faculty use these exercises in their exams, we have provided answers to roughly half of the exercises included here.
6.7 What is the value of x after each of the following statements is performed?
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 applet that calculates and displays the parking charges for each customer who parked a car in this garage yesterday. You should enter in a JTextField 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. Use the techniques described in Self-Review Exercise 6.6 to read the double value from a JTextField. 6.9 An application of method Math.floor is rounding a value to the nearest integer. The statement y = Math.floor( x + .5 ); will round the number x to the nearest integer and assign the result to y. Write an applet that reads double values and uses the preceding statement to round each of these numbers to the nearest integer. For each number processed, display both the original number and the rounded number. Use the techniques described in Self-Review Exercise 6.6 to read the double value from a JTextField. 6.10 Math.floor may be used to round a number to a specific decimal place. The statement y = Math.floor( x * 10 + .5 ) / 10; rounds x to the tenths position (the first position to the right of the decimal point). The statement y = Math.floor( x * 100 + .5 ) / 100; rounds x to the hundredths position (i.e., the second position to the right of the decimal point). Write an applet that defines four methods to round a number x in various ways:
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.
6.12 Write statements that assign random integers to the variable n in the following ranges:
6.13 For each of the following sets of integers, write a single statement that will print a number at random from the set.
6.14 Write a method integerPower( base, exponent ) that returns the value of base ^{exponent} For example, integerPower( 3, 4 ) = 3 * 3 * 3 * 3. Assume that exponent is a positive, nonzero integer and base is an integer. Method integerPower should use for or while to control the calculation. Do not use any math library methods. Incorporate this method into an applet that reads integer values from JTextFields for base and exponent from the user and performs the calculation with the integerPower method. [Note: Register for event handling on only the second JTextField. The user should interact with the program by typing numbers in both JTextFields and pressing Enter in the second JTextField.] 6.15 Define a method hypotenuse that calculates the length of the hypotenuse of a right triangle when the other two sides are given. The method should take two arguments of type double and return the hypotenuse as a double. Incorporate this method into an applet that reads integer values for side1 and side2 from JTextFields and performs the calculation with the hypotenuse method. Determine the length of the hypotenuse for each of the following triangles. [Note: Register for event handling on only the second JTextField. The user should interact with the program by typing numbers in both JTextFields and pressing Enter in the second JTextField.]
^{ } 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 applet that inputs a series of pairs of integers (one pair at a time using JTextFields). [Note: Register for event handling on only the second JTextField. The user should interact with the program by typing numbers in both JTextFields and pressing Enter in the second JTextField.] 6.17 Write an applet that inputs integers (one at a time) and passes them one at a time to method isEven, which uses the modulus operator to determine if an integer is even. The method should take an integer argument and return true if the integer is even and false otherwise. Use sentinel-controlled looping and an input dialog. 6.18 Write a method squareOfAsterisks that displays a solid square of asterisks whose side is specified in integer parameter side. For example, if side is 4, the method displays **** Incorporate this method into an applet that reads an integer value for side from the user at the keyboard and performs the drawing with the squareOfAsterisks method. Note that this method should be called from the applet's paint method and should be passed the Graphics object from paint. 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 "#", this method should print 6.20 Use techniques similar to those developed in Exercises 6.18 and 6.19 to produce a program that graphs a wide range of shapes. 6.21 Modify the program of Exercise 6.18 to draw a solid square with the fillRect method of the Graphics class. Method fillRect receives four arguments–x-coordinate, y-coordinate, width and height. Allow the user to enter the coordinates at which the square should appear. 6.22 Write program segments that accomplish each of the following:
6.23 Implement the following integer methods:
C = 5.0 / 9.0 * ( F - 32 );
F = 9.0 / 5.0 * C + 32;
[Note: This applet will require that two JTextField objects that have registered action events. When actionPerformed is invoked, the ActionEvent parameter has method getSource() to determine the GUI component with which the user interacted. Your actionPerformed method should contain an if/else structure of the following form: if ( e.getSource() == input1 ) { where input1 and input2 are JTextField references.] 6.24 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 applet that reads three values from the user and determines the smallest value. Display the result in the status bar. 6.25 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 if parameter number is a perfect number. Use this method in an applet that determines and displays all the perfect numbers between 1 and 1000. Print 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 in a JTextArea that has scrolling functionality. 6.26 An integer is said to be prime if it is divisible only by 1 and itself. For example, 2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not.
6.27 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 applet that reads a value from the user. Display the result of the method in the status bar. 6.28 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 applet that reads two values from the user. Display the result of the method in the status bar. 6.29 Write a method qualityPoints that inputs a student’s average and returns 4 if a student's average is 90—100, 3 if the average is 80—89, 2 if the average is 70—79, 1 if the average is 60—69 and 0 if the average is lower than 60. Incorporate the method into an applet that reads a value from the user. Display the result of the method in the status bar. 6.30 Write an applet that simulates coin tossing. Let the program toss the coin each time the user presses the "Toss" button. 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 the coin tossing, each side of the coin should appear approximately half the time.] 6.31 Computers are playing an increasing role in education. Write a program that will help an elementary school student learn multiplication. Use Math.random to produce two positive one-digit integers. It should then display a question in the status bar such as How much is 6 times 7? The student then types the answer into a JTextField. Your program checks the student's answer. If it is correct, draw the string "Very good!" on the applet, then ask another multiplication question. If the answer is wrong, draw the string "No. Please try again." on the applet, then let the student try the same question again 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 applet begins execution and each time the user answers the question correctly. All drawing on the applet should be performed by the paint method. 6.32 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 can be eliminated by varying the computer's dialogue to hold the student's attention. Modify the program of Exercise 6.31 so the various comments are printed for each correct answer and each incorrect answer as follows: Responses to a correct answer Very good! Responses to an incorrect answer No. Please try again. 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 structure in the paint method to issue the responses. 6.33 More sophisticated computer-aided instructions 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.32 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%, print Please ask your instructor for extra help and reset the program so another student can try the program. 6.34 Write an applet that plays the "guess the number" game as follows: Your program chooses the number to be guessed by selecting a random integer in the range 1 to 1000. The applet displays the prompt Guess a number between 1 and 1000 next to a JTextField. The player types a first guess into the JTextField and presses the Enter key. If the player's guess is incorrect, your program should display Too high. Try again. or Too low. Try again. in the status bar to help the player "zero in" on the correct answer and should clear the JTextField so the user can enter the next guess. When the user enters the correct answer, display Congratulations. You guessed the number! in the status bar and clear the JTextField so the user can play again. [Note: The guessing technique employed in this problem is similar to a binary search.] 6.35 Modify the program of Exercise 6.34 to count the number of guesses the player makes. If the number is 10 or fewer, print Either you know the secret or you got lucky! If the player guesses the number in 10 tries, print Ahah! You know the secret! If the player makes more than 10 guesses, print 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 1 to 1000 can be guessed in 10 or fewer tries. 6.36 Write a recursive method power (base, exponent) that when invoked returns base ^{exponent} for example, power( 3, 4 ) = 3 * 3 * 3 * 3. Assume that exponent is an integer greater than or equal to 1. (Hint: The recursion step would use the relationship base ^{exponent} = base · base ^{exponent} - 1 and the terminating condition occurs when exponent is equal to 1 because base1 = base Incorporate this method into an applet that enables the user to enter the base and exponent.) 6.37 (Towers of Hanoi) Every budding computer scientist must grapple with certain classic problems and the Towers of Hanoi (see Fig. 6.19) is one of the most famous of these. Legend has it that in a temple in the Far East, priests are attempting to move a stack of disks from one peg to another. The initial stack had 64 disks threaded onto one peg and arranged from bottom to top by decreasing size. The priests are attempting to move the stack from this peg to a second peg under the constraints that exactly one disk is moved at a time and at no time may a larger disk be placed above a smaller disk. A third peg is available for temporarily holding disks. Supposedly, the world will end when the priests complete their task, so there is little incentive for us to facilitate their efforts. Fig. 6.19 The Towers of Hanoi for the case with four disks.
Let us assume that the priests are attempting to move the disks from peg 1 to peg 3. We wish to develop an algorithm that will print the precise sequence of peg-to-peg disk transfers. If we were to approach this problem with conventional methods, we would rapidly find ourselves hopelessly knotted up in managing the disks. Instead, if we attack the problem with recursion in mind, it immediately becomes tractable. Moving n disks can be viewed in terms of moving only n — 1 disks (and hence the recursion) as follows:
The process ends when the last task involves moving n = 1 disk (i.e., the base case). This is accomplished by trivially moving the disk without the need for a temporary holding area. Write an applet to solve the Towers of Hanoi problem. Allow the user to enter the number of disks in a JTextField. Use a recursive tower method with four parameters:
Your program should display in a JTextArea with scrolling functionality the precise instructions it will take to move the disks from the starting peg to the destination peg. For example, to move a stack of three disks from peg 1 to peg 3, your program should print the following series of moves: 1-->3 (This means move one disk from peg 1 to peg 3.) 1--> 2 3--> 2 1--> 3 2--> 1 2--> 3 1--> 3 6.38 Any program that can be implemented recursively can be implemented iteratively, although sometimes with more difficulty and less clarity. Try writing an iterative version of the Towers of Hanoi. If you succeed, compare your iterative version with the recursive version you developed in Exercise 6.37. Investigate issues of performance, clarity and your ability to demonstrate the correctness of the programs. 6.39 (Visualizing Recursion) It is interesting to watch recursion "in action." Modify the factorial method of Fig. 6.12 to print its local variable and recursive call parameter. For each recursive call, display the outputs on a separate line and add a level of indentation. Do your utmost to make the outputs clear, interesting and meaningful. Your goal here is to design and implement an output format that helps a person understand recursion better. You may want to add such display capabilities to the many other recursion examples and exercises throughout the text. 6.40 The greatest common divisor of integers x and y is the largest integer that evenly divides both x and y. Write a recursive method gcd that returns the greatest common divisor of x and y. The gcd of x and y is defined recursively as follows: If y is equal to 0, then gcd( x, y ) is x; otherwise, gcd( x, y ) is gcd( y, x % y ), where % is the modulus operator. Use this method to replace the one you wrote in the applet of Exercise 6.28. 6.41 Exercises 6.31 through 6.33 developed a computer-assisted instruction program to teach an elementary school student multiplication. This exercise suggests enhancements to that program.
6.42 Write method distance, which calculates 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 applet that enables the user to enter the coordinates of the points. 6.43 What does the following method do? // Parameter b must be a positive 6.44 After you determine what the program of Exercise 6.43 does, modify the method to operate properly after removing the restriction of the second argument being nonnegative. Also, incorporate the method into an applet that enables the user to enter two integers and test the method. 6.45 Write an application that tests as many of the math library methods in Fig. 6.2 as you can. Exercise each of these methods by having your program print out tables of return values for a diversity of argument values. 6.46 Find the error in the following recursive method and explain how to correct it: public int sum( int n ) 6.47 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 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 print the new bankBalance. If the player loses, decrease bankBalance by wager, print the new bankBalance, check if bankBalance has become zero, and if so, print the message "Sorry. You busted!" As the game progresses, print 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.48 Write an applet that uses a method circleArea to prompt the user for the radius of a circle and to calculate and print the area of that circle. |
Included below are answers to approximately half the of the exercises in the Cyber Classroom. We are not able to include answers to every exercise because college faculty use these exercises in their classroom exams.
6.7 What is the value of x after each of the following statements is performed?
// Exercise 6.9 Solution // Test.java // Program tests Math.floor import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Test extends JApplet implements ActionListener { JTextField input; JLabel inputLabel; public void init() { input = new JTextField( 4 ); input.addActionListener( this ); inputLabel = new JLabel( "Enter a decimal number:" ); getContentPane().setLayout( new FlowLayout() ); getContentPane().add( inputLabel ); getContentPane().add( input ); } public void actionPerformed( ActionEvent e ) { double x = Double.parseDouble( input.getText() ); showStatus( "Number: " + x + " Math.floor( x + .5 ): " + String.valueOf( Math.floor( x + .5 ) ) ); } }
6.12 Write statements that assign random integers to the variable n in the following ranges:
// Exercise 6.15 Solution // Triangle.java // Program calculates the hypotenuse of // a right triangle. import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Triangle extends JApplet implements ActionListener { JTextField sideInput, side2Input; JLabel sidePrompt, sidePrompt2; public void init() { sideInput = new JTextField( 4 ); side2Input = new JTextField( 4 ); side2Input.addActionListener( this ); sidePrompt = new JLabel( "Enter side 1: " ); sidePrompt2 = new JLabel( "Enter side 2: " ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); c.add( sidePrompt ); c.add( sideInput ); c.add( sidePrompt2 ); c.add( side2Input ); } public void actionPerformed( ActionEvent e ) { double side1, side2; side1 = Double.parseDouble( side2Input.getText() ); side2 = Double.parseDouble( sideInput.getText() ); double h = hypotenuse( side1, side2 ); showStatus( "Hypotenuse is : " + h ); } public double hypotenuse( double s1, double s2 ) { double hypotSquared = Math.pow( s1, 2 ) + Math.pow( s2, 2 ); return Math.sqrt( hypotSquared ); } }
// Exercise 6.17 Solution // EvenOdd.java // Determines if a number is odd or even import javax.swing.*; import java.awt.*; import java.awt.event.*; public class EvenOdd extends JApplet implements ActionListener{ private JTextField input; private JLabel prompt; public void init() { input = new JTextField( 4 ); input.addActionListener( this ); prompt = new JLabel( "Enter number: " ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); c.add( prompt ); c.add( input ); } public void actionPerformed( ActionEvent e ) { int number = Integer.parseInt( input.getText() ); String result = ""; if ( isEven( number ) == true ) result = number + " is even"; else result = number + " is odd "; showStatus( result ); } public boolean isEven( int num ) { if ( num % 2 == 0 ) return true; return false; } }
// Exercise 6.18 Solution // Square.java // Program draws a square of asterisks import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Square extends JApplet { int size; public void init() { String input = JOptionPane.showInputDialog( "Enter square size:" ); size = Integer.parseInt( input ); } public void squareOfAsterisks( Graphics g ) { int y = 50, x = 5; for ( int a = 1; a <= size * size; a++ ) { g.drawString( "*", x += 5, y ); if ( a % size == 0 ) { y += 10; x = 5; } } } public void paint( Graphics g ) { squareOfAsterisks( g ); } }
// Exercise 6.22 Solution // Digits.java // Program separtes a four digit number // into its individual digits. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Digits extends JApplet implements ActionListener { JTextField input; JLabel prompt, display; public void init() { input = new JTextField( 6 ); input.addActionListener( this ); display = new JLabel(); prompt = new JLabel( "Enter a five digit number:" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); c.add( prompt ); c.add( input ); c.add( display ); } public void actionPerformed( ActionEvent e ) { int number = Integer.parseInt( input.getText() ); if ( number >= 1 && number <= 99999 ) { showStatus( "" ); displayDigits( number ); } else { showStatus( "Invalid input" ); display.setText( "" ); } } // Part A public int quotient( int a, int b ) { return a / b; } // Part B public int remainder( int a, int b ) { return a % b; } // Part C public void displayDigits( int number ) { int divisor = 10000, digit, x = 5, y = 80; String s = ""; while ( divisor >= 1 ) { digit = quotient( number, divisor ); s += digit + " "; number = remainder( number, divisor ); divisor = quotient( divisor, 10 ); } display.setText( s ); } }
// Exercise 6.23 Solution // Convert.java // Program converts Fahrenheit to Celcius // and vice versa. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Convert extends JApplet implements ActionListener { JTextField cInput, fInput; JLabel cLabel, fLabel; public void init() { cInput = new JTextField( 4 ); fInput = new JTextField( 4 ); cInput.addActionListener( this ); fInput.addActionListener( this ); cLabel = new JLabel( "Celcius:" ); fLabel = new JLabel( "Fahrenheit:" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); c.add( cLabel ); c.add( cInput ); c.add( fLabel ); c.add( fInput ); } public void actionPerformed( ActionEvent e ) { if ( e.getSource() == cInput ) { int c = Integer.parseInt( cInput.getText() ); fInput.setText( String.valueOf( celcius( c ) ) ); showStatus( "Celcius to Fahrenheit" ); } else if ( e.getSource() == fInput ) { int f = Integer.parseInt( fInput.getText() ); cInput.setText( String.valueOf( fahrenheit( f ) ) ); showStatus( "Fahrenheit to Celcius" ); } } public int celcius( int cTemp ) { return ( ( int ) ( 9.0 / 5.0 * cTemp + 32 ) ); } public int fahrenheit( int fTemp ) { return ( ( int ) ( 5.0 / 9.0 * ( fTemp - 32 ) ) ); } }
// Exercise 6.25 Solution // PerfectNum.java // Program determines if a number // is a "perfect" number import javax.swing.*; import java.awt.*; public class PerfectNum extends JApplet { JTextArea outputArea; JScrollPane scroller; public void init() { outputArea = new JTextArea( 17, 40 ); scroller = new JScrollPane( outputArea ); int y = 5; String output = ""; for ( int a = 2; a <= 1000; a++ ) if ( perfect( a ) == true ) output += "\n" + a + " is perfect."; outputArea.setText( output ); getContentPane().add( scroller ); } public boolean perfect( int value ) { int factorSum = 1; for ( int b = 2; b <= value / 2; b++ ) if ( value % b == 0 ) factorSum += b; if ( factorSum == value ) return true; return false; } }
}
// Exercise 6.27 Solution // Reverse.java // Program takes a four digit number // and prints out its digits reversed import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Reverse extends JApplet implements ActionListener { JTextField input; JLabel prompt; int number; public void init() { input = new JTextField( 6 ); input.addActionListener( this ); prompt = new JLabel( "Enter a four digit number: " ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); c.add( prompt ); c.add( input ); } public void actionPerformed( ActionEvent e ) { number = Integer.parseInt( input.getText() ); reverseDigits(); } public void reverseDigits() { int digit1 = 0, digit2 = 0, digit3 = 0, digit4 = 0, factor = 1000, value = 0; while ( factor >= 1 ) { int temp = number / factor; switch ( factor ) { case 1000: digit4 = temp; break; case 100: digit3 = temp * 10; break; case 10: digit2 = temp * 100; break; case 1: digit1 = temp * 1000; break; } number %= factor; factor /= 10; } if ( digit1 == 0 ) // special case when last digit initially is 0 showStatus( String.valueOf( 0 ) + String.valueOf( digit2 / 100 ) + String.valueOf( digit3 / 10 ) + String.valueOf( digit4 ) ); else showStatus( String.valueOf(digit1 + digit2 + digit3 + digit4) ); } }
// Exercise 6.29 Solution // Average.java // Program displays a number // representing the student's average import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Average extends JApplet implements ActionListener { JTextField input; JLabel prompt; public void init() { input = new JTextField( 4 ); input.addActionListener( this ); prompt = new JLabel( "Enter average:" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); c.add( prompt ); c.add( input ); } public void actionPerformed( ActionEvent e ) { int number = Integer.parseInt( input.getText() ); if ( number >= 0 && number <= 100 ) showStatus( "Point is: " + qualityPoints( number ) ); else showStatus( "Invalid input." ); } public int qualityPoints( int grade ) { if ( grade >= 90 ) return 4; else if ( grade >= 80 ) return 3; else if ( grade >= 70 ) return 2; else if ( grade >= 60 ) return 1; else return 0; } }
// Exercise 6.30 Solution // Coin.java // Program simulates tossing a coin. import javax.swing.*; import java.awt.event.*; public class Coin extends JApplet implements ActionListener { int heads, tails; JButton b; public void init() { b = new JButton( "Toss" ); b.addActionListener( this ); getContentPane().add( b ); } public void actionPerformed( ActionEvent e ) { if ( flip() == true ) ++heads; else ++tails; showStatus( "Heads: " + heads + " Tails: " + tails ); } public boolean flip() { if ( ( int ) ( Math.random() * 2 ) == 1 ) return true; else return false; } }
// Exercise 6.36 Solution // Exponential.java // Program calculates exponents import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Exponential extends JApplet implements ActionListener { JTextField baseInput, expInput; JLabel basePrompt, expPrompt; public void init() { baseInput = new JTextField( 4 ); expInput = new JTextField( 4 ); expInput.addActionListener( this ); basePrompt = new JLabel( "Enter base: " ); expPrompt = new JLabel( "Enter exponent: " ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); c.add( basePrompt ); c.add( baseInput ); c.add( expPrompt ); c.add( expInput ); } public void actionPerformed( ActionEvent e ) { int base, exponent; base = Integer.parseInt( baseInput.getText() ); exponent = Integer.parseInt( expInput.getText() ); if ( exponent > 0 ) { int result = power( base, exponent ); showStatus( "Value is " + result ); } else showStatus( "Invalid Exponent." ); } public int power( int b, int exp ) { if ( exp == 1 ) return b; else return b * power( b, exp - 1 ); } }
// Exercise 6.40 Solution // Divisor.java // Program recursively finds the greatest // common divisor of two numbers. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Divisor extends JApplet implements ActionListener { JTextField input1, input2; JLabel label1, label2; public void init() { input1 = new JTextField( 4 ); input2 = new JTextField( 4 ); input2.addActionListener( this ); label1 = new JLabel( "Enter first number:" ); label2 = new JLabel( "Enter second number:" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); c.add( label1 ); c.add( input1 ); c.add( label2 ); c.add( input2 ); } public void actionPerformed( ActionEvent e ) { int num1, num2; num1 = Integer.parseInt( input1.getText() ); num2 = Integer.parseInt( input2.getText() ); showStatus( "GCD is: " + gcd( num1, num2 ) ); } public int gcd( int x, int y ) { if ( y == 0 ) return x; else return gcd( y, x % y ); } }
// Exercise 6.42 Solution // Points.java // Program calculates the distance // between two points import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Points extends JApplet implements ActionListener { JTextField x1Input, x2Input, y1Input, y2Input; JLabel labelX1, labelX2, labelY1, labelY2; double theDistance; boolean enabled; public void init() { x1Input = new JTextField( 4 ); x2Input = new JTextField( 4 ); y1Input = new JTextField( 4 ); y2Input = new JTextField( 4 ); y2Input.addActionListener( this ); labelX1 = new JLabel( "Enter X1: " ); labelY1 = new JLabel( "Enter Y1: " ); labelX2 = new JLabel( "Enter X2: " ); labelY2 = new JLabel( "Enter Y2: " ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); c.add( labelX1 ); c.add( x1Input ); c.add( labelY1 ); c.add( y1Input ); c.add( labelX2 ); c.add( x2Input ); c.add( labelY2 ); c.add( y2Input ); } public void actionPerformed( ActionEvent e ) { enabled = false; double tempX1, tempX2, tempY1, tempY2; tempX1 = Double.parseDouble( x1Input.getText() ); tempY1 = Double.parseDouble( y1Input.getText() ); tempX2 = Double.parseDouble( x2Input.getText() ); tempY2 = Double.parseDouble( y2Input.getText() ); theDistance = distance( tempX1, tempY1, tempX2, tempY2 ); showStatus( "Distance is " + theDistance ); } public double distance( double x1, double y1, double x2, double y2 ) { double d; enabled = true; d = Math.sqrt( Math.pow( ( x1 - x2 ), 2 ) + Math.pow( ( y1 - y2 ), 2 ) ); return d; } }
// Exercise 6.48 Solution // Circle.java // Program calulates the area of a circle import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Circle extends JApplet implements ActionListener { JTextField input; JLabel instruction; public void init() { input = new JTextField( 4 ); input.addActionListener( this ); instruction = new JLabel( "Enter the radius: " ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); c.add( instruction ); c.add( input ); } public void actionPerformed( ActionEvent e ) { showStatus( "" ); int r = Integer.parseInt( input.getText() ); circleArea( r ); } public void circleArea( int radius ) { showStatus( "Area is " + radius * radius * Math.PI ); } }