252 Methods Chapter 6 48). Method squarereceives the

252 Methods Chapter 6 48). Method squarereceives the copy of the value of counterin the parameter y. Then, square calculates y*y (line 46). Method square uses a return statement to return (i.e., give back) the result of the calculation to the statement in init that invoked square. In method init, the return value is assigned to variable result. Lines 34 35 concatenate “The square of “, the value of counter, “is “, the value of result and a newline character to the end of output. This process repeats for each iteration of the forrepetition structure. Line 39 uses method setTextto set outputArea s text to the Stringoutput. 1 // Fig. 6.3: SquareIntegers.java 2 // A programmer-defined square method 3 4 // Java core packages 5 import java.awt.Container; 6 7 // Java extension packages 8 import javax.swing.*; 9 10 public class SquareIntegers extends JApplet { 11 12 // set up GUI and calculate squares of integers from 1 to 10 13 public void init() 14 { 15 // JTextArea to display results 16 JTextArea outputArea = new JTextArea(); 17 18 // get applet’s content pane (GUI component display area) 19 Container container = getContentPane(); 20 21 // attach outputArea to container 22 container.add( outputArea ); 23 24 int result; // store result of call to method square 25 String output = “”; // String containing results 26 27 // loop 10 times 28 for ( int counter = 1; counter <= 10; counter++ ) { 29 30 // calculate square of counter and store in result 31 result = square( counter ); 32 33 // append result to String output 34 output += “The square of ” + counter + 35 ” is ” + result + “n”; 36 37 } // end for structure 38 39 outputArea.setText( output ); // place results in JTextArea 40 41 } // end method init 42 Fig. 6.3 Using programmer-defined method square(part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Leave a Reply