The User-Defined Method for Finding Squares

 

 

Finding Squares.  Now we start with a relatively simple applet to find squares of a series of numbers.  The squares are computed within a method.  The other innovation in the code is that the output is displayed within the applet window rather than in a JOptionPane.

This first set of code is the program for SquareInt.java.

 

import java.awt.Container;
import javax.swing.*;

public class SquareInt extends JApplet
{

public void init( )
{

String output = "";

JTextArea outputArea = new JTextArea( 10, 30 );

// get the applet's GUI component display area
Container c = getContentPane( );

// attach output area to container c
c.add( outputArea );

int result;

for ( int i=1; i <= 15; i++ )
{

// call the square method at each iteration of the loop
// return the result into the integer result

result = square( i );
// echo the input and display the result
// using control characters

output = output + "The square of\t" + i + "\tis\t" + result + "\n";

}

outputArea.setText(output);

} // end method init( )

// square method definition

public int square( int y )
{

return y * y;

} // end method square( )

} // end class SquareInt

 

Before we discuss the program you should develop the HTML file called SquareInt.html.

 

<html>
<applet code="SquareInt.class" width=300 height=350>
</applet>
</html>

 

The results of the program look like the following.

 

 

The code can be described as the following.
  • The first section imports the necessary classes from the appropriate packages
    • all of the swing package
    • the Container classes from the package awt - abstract windowing toolkit
  • The inclusive class is defined as extending JApplet from the swing package
  • Variables and objects are declared and initialized
    • a string for output
    • outputArea is an instantiation of the class JTextArea from the package swing
    • an object Container c is developed using the awt package
    • the JTextArea outputArea is added to the Container called c
  • A for loop that runs from 1 to 15 is developed
    • Within this for loop each counter value is squared by calling the method square( ) and returning the result
    • Each result and the input that drove it are added to the output string using control characters for display
  • the outputArea's contents are set to the the output string

 

  • the method public int square( int y ) is declared and defined
  • each time it is called the value that is passed into it is squared and returned

Notice how the variable  y used within the square( ) method is not used anyplace else.  It's scope is said to be the method square( ).  It is a local variable, local to that method

The variable int i is declared within the init( ) method and has scope only within it.  It is local to that method.

This terminology is important and we will start to consistently discuss these sorts of issues.