Archive for the 'PHP5' Category

Free web host - 308 Methods Chapter 6 6.23 Implement the following

Monday, January 7th, 2008

308 Methods Chapter 6 6.23 Implement the following integer methods: a) Method celsius returns the Celsius equivalent of a Fahrenheit temperature, using the calculation C =5.0 / 9.0 * ( F - 32 ); b) Method fahrenheitreturns the Fahrenheit equivalent of a Celsius temperature, using the calculation F =9.0 / 5.0 * C + 32; c) Use these methods to write an applet that enables the user to enter either a Fahrenheit temperature and display the Celsius equivalent or enter a Celsius temperature and display the Fahrenheit equivalent. [Note: This applet will require 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 form if ( actionEvent.getSource() == input1 ) { // process input1 interaction here } else { // e.getSource() == input2 // process input2 interaction here } 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. a) Write a method that determines if a number is prime. b) Use this method in an applet that determines and prints all the prime numbers between 1 and 10,000. How many of these 10,000 numbers do you really have to test before being sure that you have found all the primes? Display the results in a JTextArea that has scrolling functionality. c) Initially, you might think that n/2 is the upper limit for which you must test to see if 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.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. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Chapter 6 Methods 307 (Web hosting colocation) 6.16 Write a method

Sunday, January 6th, 2008

Chapter 6 Methods 307 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 only in the second JTextField.] 6.17 Write a method isEven that 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. Incorporate this method into an applet that inputs a series integers (one at a time using a JTextField). 6.18 Write a method squareOfAsterisksthat displays a solid square of asterisks whose side is specified in integer parameter side. For example, if sideis 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 fillCharacteris # , the method should print ##### ##### ##### ##### ##### 6.20 Use techniques similar to those developed in Exercise 6.18 and Exercise 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 input the coordinates at which the square should appear. 6.22 Write program segments that accomplish each of the following tasks: a) Calculate the integer part of the quotient when integer a is divided by integer b. b) Calculate the integer remainder when integer ais divided by integer b. c) Use the program pieces developed in parts a) and b) to write a method displayDig its that receives an integer between 1and 99999 and prints it as a series of digits, each pair of which is separated by two spaces. For example, the integer 4562 should be printed as 4 5 6 2 d) Incorporate the method developed in part c) into an applet that inputs an integer from an input dialog and invokes displayDigitsby passing the method the integer entered. Display the results in a message dialog. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Apache web server - 306 Methods Chapter 6 6.11 Answer each of

Saturday, January 5th, 2008

306 Methods Chapter 6 6.11 Answer each of the following questions: a) What does it mean to choose numbers at random? b) Why is the Math.randommethod useful for simulating games of chance? c) Why is it often necessary to scale and/or shift the values produced by Math.random? d) 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: a) 1 = n = 2 b) 1 = n = 100 c) 0 = n = 9 d) 1000 = n = 1112 e) 1 = n = 1 f) 3 = n = 11 6.13 For each of the following sets of integers, write a single statement that will print a number at random from the set: a) 2, 4, 6, 8, 10. b) 3, 5, 7, 9, 11. c) 6, 10, 14, 18, 22. 6.14 Write a method integerPower( base,exponent )that returns the value of base exponent For example, integerPower(3,4)calculates 34 (or 3*3*3*3). Assume that exponent is a positive, nonzero integer and that baseis an integer. Method integerPowershould 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 integerPowermethod. [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 only in the second JTextField.] 6.15 Define a method hypotenusethat calculates the length of the hypotenuse of a right triangle when the other two sides are given (sample data appear in Fig. 6.22). The method should take two arguments of type doubleand return the hypotenuse as a double. Incorporate this method into an applet that reads values for side1and 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 only in the second JTextField.] Triangle Side 1 Side 2 1 3.0 4.0 2 5.0 12.0 3 8.0 15.0 Fig. 6.2222 Values for the sides of triangles in Exercise 6.15. Fig. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Chapter 6 (Web site development) Methods 305 EXERCISES 6.7 What is

Saturday, January 5th, 2008

Chapter 6 Methods 305 EXERCISES 6.7 What is the value of x after each of the following statements is performed? a) x = Math.abs( 7.5 ); b) x = Math.floor( 7.5 ); c) x = Math.abs( 0.0 ); d) x = Math.ceil( 0.0 ); e) x = Math.abs( -6.4 ); f) x = Math.ceil( -6.4 ); g) 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 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 calculateChargesto determine the charge for each customer. 6.9 An application of method Math.flooris 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 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 + .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 + .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: a) roundToInteger( number ) b) roundToTenths( number ) c) roundToHundredths( number ) d) 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. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

304 Methods Chapter 6 d) Error: Both the

Friday, January 4th, 2008

304 Methods Chapter 6 d) Error: Both the semicolon after the right parenthesis that encloses the parameter list and redefining the parameter a in the method definition are incorrect. Correction: Delete the semicolon after the right parenthesis of the parameter list, and delete the declaration float a;. e) Error: The method returns a value when it is not supposed to. Correction: Change the return type to int. 6.6 The following solution calculates the volume of a sphere using the radius entered by the user: 1 // Exercise 6.6: SphereTest.java 2 3 // Java core packages 4 import java.awt.*; 5 import java.awt.event.*; 6 7 // Java extension packages 8 import javax.swing.*; 9 10 public class SphereTest extends JApplet 11 implements ActionListener { 12 13 JLabel promptLabel; 14 JTextField inputField; 15 16 public void init() 17 { 18 Container container = getContentPane(); 19 container.setLayout( new FlowLayout() ); 20 21 promptLabel = new JLabel( “Enter sphere radius: ” ); 22 inputField = new JTextField( 10 ); 23 inputField.addActionListener( this ); 24 container.add( promptLabel ); 25 container.add( inputField ); 26 } 27 28 public void actionPerformed( ActionEvent actionEvent ) 29 { 30 double radius = 31 Double.parseDouble( actionEvent.getActionCommand() ); 32 33 showStatus( “Volume is ” + sphereVolume( radius ) ); 34 } 35 36 public double sphereVolume( double radius ) 37 { 38 double volume = 39 ( 4.0 / 3.0 ) * Math.PI * Math.pow( radius, 3 ); 40 41 return volume; 42 } 43 } Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Frontpage web hosting - Chapter 6 Methods 303 39 System.out.println( “Math.pow( 2,

Thursday, January 3rd, 2008

Chapter 6 Methods 303 39 System.out.println( “Math.pow( 2, 7 ) = ” + 40 Math.pow( 2, 7 ) ); 41 System.out.println( “Math.pow( 9, .5 ) = ” + 42 Math.pow( 9, .5 ) ); 43 System.out.println( “Math.sin( 0.0 ) = ” + 44 Math.sin( 0.0 ) ); 45 System.out.println( “Math.sqrt( 25.0 ) = ” + 46 Math.sqrt( 25.0 ) ); 47 System.out.println( “Math.tan( 0.0 ) = ” + 48 Math.tan( 0.0 ) ); 49 } 50 } Math.abs( 23.7 ) = 23.7 Math.abs( 0.0 ) = 0 Math.abs( -23.7 ) = 23.7 Math.ceil( 9.2 ) = 10 Math.ceil( -9.8 ) = -9 Math.cos( 0.0 ) = 1 Math.exp( 1.0 ) = 2.71828 Math.exp( 2.0 ) = 7.38906 Math.floor( 9.2 ) = 9 Math.floor( -9.8 ) = -10 Math.log( 2.718282 ) = 1 Math.log( 7.389056 ) = 2 Math.max( 2.3, 12.7 ) = 12.7 Math.max( -2.3, -12.7 ) = -2.3 Math.min( 2.3, 12.7 ) = 2.3 Math.min( -2.3, -12.7 ) = -12.7 Math.pow( 2, 7 ) = 128 Math.pow( 9, .5 ) = 3 Math.sin( 0.0 ) = 0 Math.sqrt( 25.0 ) = 5 Math.tan( 0.0 ) = 0 6.4 a) double hypotenuse( double side1, double side2 ) b) int smallest( int x, int y, int z ) c) void instructions() d) float intToFloat( int number ) 6.5 a) Error: Method h is defined in method g. Correction: Move the definition of h outside the definition of g. b) Error: The method is supposed to return an integer, but does not. Correction: Delete 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; c) Error: The result of n + sum(n-1) is not returned by this recursive method, resulting in a syntax error. Correction: Rewrite the statement in the else clause as return n + sum( n - 1); Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

302 Methods Chapter 6 6.6 Write a complete (Business web hosting)

Thursday, January 3rd, 2008

302 Methods Chapter 6 6.6 Write a complete Java applet to prompt the user for the double radius of a sphere, and call method sphereVolume to calculate and display the volume of that sphere using the assignment volume = ( 4.0 / 3.0 ) * Math.PI * Math.pow( radius, 3 ) The user should input the radius through a JTextField. ANSWERS TO SELF-REVIEW EXERCISES 6.1 a) methods and classes. b) method call. c) local variable. d) return. e) void. f) scope. g) return;or return expression;or encountering the closing right brace of a method. h) init. i) Math.random. j) start. k) paint. l) automatic. m) repaint. n) stop. o) recursive. p) base. q) overloading. r) final. 6.2 a) Class scope. b) Block scope. c) Class scope. d) Class scope. e) Block scope. 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 public static void main( String args[] ) 6 { 7 System.out.println( “Math.abs( 23.7 ) = ” + 8 Math.abs( 23.7 ) ); 9 System.out.println( “Math.abs( 0.0 ) = ” + 10 Math.abs( 0.0 ) ); 11 System.out.println( “Math.abs( -23.7 ) = ” + 12 Math.abs( -23.7 ) ); 13 System.out.println( “Math.ceil( 9.2 ) = ” + 14 Math.ceil( 9.2 ) ); 15 System.out.println( “Math.ceil( -9.8 ) = ” + 16 Math.ceil( -9.8 ) ); 17 System.out.println( “Math.cos( 0.0 ) = ” + 18 Math.cos( 0.0 ) ); 19 System.out.println( “Math.exp( 1.0 ) = ” + 20 Math.exp( 1.0 ) ); 21 System.out.println( “Math.exp( 2.0 ) = ” + 22 Math.exp( 2.0 ) ); 23 System.out.println( “Math.floor( 9.2 ) = ” + 24 Math.floor( 9.2 ) ); 25 System.out.println( “Math.floor( -9.8 ) = ” + 26 Math.floor( -9.8 ) ); 27 System.out.println( “Math.log( 2.718282 ) = ” + 28 Math.log( 2.718282 ) ); 29 System.out.println( “Math.log( 7.389056 ) = ” + 30 Math.log( 7.389056 ) ); 31 System.out.println( “Math.max( 2.3, 12.7 ) = v + 32 Math.max( 2.3, 12.7 ) ); 33 System.out.println( “Math.max( -2.3, -12.7 ) = ” + 34 Math.max( -2.3, -12.7 ) ); 35 System.out.println( “Math.min( 2.3, 12.7 ) = ” + 36 Math.min( 2.3, 12.7 ) ); 37 System.out.println( “Math.min( -2.3, -12.7 ) = ” + 38 Math.min( -2.3, -12.7 ) ); Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Simple web server - Chapter 6 Methods 301 7 8 for (

Wednesday, January 2nd, 2008

Chapter 6 Methods 301 7 8 for ( x = 1; x <= 10; x++ ) { 9 g.drawString( cube( x ), 25, yPos ); 10 yPos += 15; 11 } 12 } 13 14 public int cube( int y ) 15 { 16 return y * y * y; 17 } 18 } 6.3 Write an application that tests if the examples of the math-library method calls shown in Fig. 6.2 actually produce the indicated results. 6.4 Give the method header for each of the following methods: a) Method hypotenuse, which takes two double-precision, floating-point arguments side1 and side2 and returns a double-precision, floating-point result. b) Method smallest, which takes three integers x, y and zand returns an integer. c) Method instructions, which does not take any arguments and does not return a val ue. [Note: Such methods are commonly used to display instructions to a user.] d) Method intToFloat, which takes an integer argument number and returns a floating- point result. 6.5 Find the error in each of the following program segments. Explain how to correct the error. a) int g() { System.out.println( “Inside method g” ); int h() { System.out.println( “Inside method h” ); } } b) int sum(int x, int y ) { int result; result = x + y; } c) intsum( int n ) { if ( n == 0 ) return 0; else n + sum( n - 1 ); } d) void f( float a ); { float a; System.out.println( a ); } e) void product() { int a = 6, b = 5, c = 4, result; result = a * b * c; System.out.println( “Result is ” + result ); return result; } Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

300 Methods Chapter 6 showStatus method of JApplet (Web site traffic)

Tuesday, January 1st, 2008

300 Methods Chapter 6 showStatus method of JApplet startmethod of JApplet signature static storage duration simulation stop method of JApplet software engineering update method of JApplet software reusability void SELF-REVIEW EXERCISES 6.1 Fill in the blanks in each of the following statements: a) Program modules in Java are called and . b) A method is invoked with a . c) A variable known only within the method in which it is defined is called a . d) The statement in a called method can be used to pass the value of an expres sion back to the calling method. e) The keyword indicates that a method does not return a value. f) The of an identifier is the portion of the program in which the identifier can be used. g) The three ways to return control from a called method to a caller are , and . h) The method is invoked once when an applet begins execution. i) The method produces random numbers. j) The method is invoked each time the user of a browser revisits the HTML page on which an applet resides. k) The method is invoked to draw on an applet. l) Variables declared in a block or in a method s parameter list are of duration. m) The method invokes the applet s update method, which in turn invokes the applet s paintmethod. n) The method is invoked for an applet each time the user of a browser leaves an HTML page on which the applet resides. o) A method that calls itself either directly or indirectly is a method. p) A recursive method typically has two components: one that provides a means for the re cursion to terminate by testing for a case and one that expresses the problem as a recursive call for a slightly simpler problem than does the original call. q) In Java, it is possible to have various methods with the same name that each operate on different types and/or numbers of arguments. This feature is called method . r) The qualifier is used to declare read-only variables. 6.2 For the following program, state the scope (either class scope or block scope) of each of the following elements: a) the variable x. b) the variable y. c) the method cube. d) the method paint. e) the variable yPos. 1 public class CubeTest extends JApplet { 2 int x; 4 public void paint( Graphics g ) 5 { 6 int yPos = 25; Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Chapter 6 Methods 299 The applet s init

Tuesday, January 1st, 2008

Chapter 6 Methods 299 The applet s init method is called once by the applet container when an applet is loaded for execution. It performs initialization of an applet. The applet s start method is called after the init method completes execution and every time the user of the browser returns to the HTML page on which the applet resides (after browsing another HTML page). The applet s paint method is called after the init method completes execution and the start method has started executing to draw on the applet. It is also called every time the applet needs to be repainted. The applet s stop method is called when the applet should suspend execution normally, when the user of the browser leaves the HTML page on which the applet resides. The applet s destroymethod is called when the applet is being removed from memory normally, when the user of the browser exits the browsing session. Method repaint can be called in an applet to cause a fresh call to paint. Method repaint invokes another method called update and passes it the Graphics object. The update method invokes the paint method and passes it the Graphics object. TERMINOLOGY ActionEvent class Math class methods ActionListener interface Math.E actionPerformed method Math.PI argument in a method call Math.random method automatic duration method automatic variable method call base case in recursion method-call operator, () block method declaration block scope method definition call a method method overloading called method mixed-type expression caller modular program calling method named constant class overloading class scope paintmethod of JApplet coercion of arguments parameter in a method definition constant variable programmer-defined method copy of a value promotion rules destroy method of JApplet random-number generation divide and conquer read-only variable duration recursion element of chance recursion step factorial method recursive call final recursive method FlowLayout class reference parameter init method of JApplet reference types invoke a method repaint method of JApplet iteration return Java API (Java class library) return-value type JButton class of package javax.swing scaling JLabel class of package javax.swing scope JTextField class of package javax.swing setLayoutmethod of JApplet local variable shifting Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01