280 Methods Chapter 6 7 // Java extension (Web hosting asp)

280 Methods Chapter 6 7 // Java extension packages 8 import javax.swing.*; 9 10 public class FactorialTest extends JApplet { 11 JTextArea outputArea; 12 13 // initialize applet by creating GUI and calculating factorials 14 public void init() 15 { 16 outputArea = new JTextArea(); 17 18 Container container = getContentPane(); 19 container.add( outputArea ); 20 21 // calculate the factorials of 0 through 10 22 for ( long counter = 0; counter <= 10; counter++ ) 23 outputArea.append( counter + “! = ” + 24 factorial( counter ) + “n” ); 25 26 } // end method init 27 28 // Recursive definition of method factorial 29 public long factorial( long number ) 30 { 31 // base case 32 if ( number <= 1 ) 33 return 1; 34 35 // recursive step 36 else 37 return number * factorial( number -1 ); 38 39 } // end method factorial 40 41 } // end class FactorialTest Fig. 6.12Calculating factorials with a recursive method (part 2 of 2). Fig. 6.12 Method factorial(line 29) receives a parameter of type longand returns a result of type long. As can be seen in Fig. 6.12, factorial values become large quickly. We chose data type longso the program can calculate factorials greater than 20!. Unfortunately, the Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Leave a Reply