The Top-Down Approach to Programming
When cleaning a house, the main task might be called CLEAN HOUSE. Thinking about cleaning an entire house, however, can be overwhelming. So, to make the task easier, you can break it down into a number of smaller steps. These steps might be CLEAN LIVING ROOM, CLEAN BEDROOM, CLEAN KITCHEN, and CLEAN BATHROOM.
After breaking the housecleaning task down into room-by-room steps, you have a better idea of what to do. But cleaning a room is also a pretty big task-especially if it hasn't been done in a while or if you have cats coughing up fur balls all over the place. So why not break each room step down, too? For example, cleaning the living room could be broken down into PICK UP ROOM, DUST AND POLISH, CLEAN FURNITURE, and VACUUM RUG.
After breaking each room's cleaning down into steps, your housecleaning job is organized much like a pyramid, with the general task on the top. As you work your way down the pyramid, from the main task to the room-by-room list and finally to the tasks for each room, the tasks get more and more specific.
Of course, when cleaning a house, you don't usually write a list of steps. If you're an efficient housecleaner, the steps are organized in your mind. (If you clean house like I do, there are only two steps: TURN ON TV and COLLAPSE ON COUCH.) However, when writing a program, which is a more conceptual task, you may not have a clear idea of exactly what needs to be done. This can lead to your being overwhelmed by the project.
Breaking programming tasks down into steps, or modules, is called modular programming. And when you break your program's modules down into even smaller modules-as we did with the task of cleaning a house-you're using a top-down approach to program design. By using top-down programming techniques, you can write any program as a series of small, easy-to-handle tasks. In Java, the basic unit for organizing code in a top-down manner is the function.
Here is a good example of a program being broken down in modules.
import java.awt.*;
import java.applet.*;
import java.lang.Math;
public class applet15 extends Applet
{
int guesses;
int number;
int guess; TextField textField1;
public void init()
{
textField1 = new TextField(10);
add(textField1);
textField1.setText("50");
guesses = 0;
number = CreateNumber();
}
public void paint(Graphics g)
{
DrawInstructions(g); guess = GetGuess();
ShowMessage(g, guess);
}
////////////////////////////////////////
// Private methods.
////////////////////////////////////////
void DrawInstructions(Graphics g)
{
g.drawString("Try to guess the number I am", 48, 65);
g.drawString("thinking of. The number will be", 48, 80);
g.drawString("between 0 and 100. You have an", 48, 95);
g.drawString("unlimited number of tries.", 48, 110);
g.drawString("Good Luck.", 95, 140);
g.drawString("the number is "+number,95,300);
}
int GetGuess()
{ String s = textField1.getText(); int num = Integer.parseInt(s);
return num;
}
int CreateNumber()
{
float n = (float)Math.random();
number = (int)(n * 100 + 1);
return number;
}
void ShowMessage(Graphics g, int guess)
{
String s = "Guesses so far: ";
s += String.valueOf(guesses);
g.drawString(s, 80, 170);
if (guess < number)
g.drawString("Your guess is too low.", 70, 185);
else if (guess > number)
g.drawString("Your guess is too high.", 70, 185);
else
{ g.drawString("You guessed the number!", 65, 185);
System.exit(0); }
}
public boolean action(Event event, Object arg)
{
++guesses;
repaint();
return true;
} }
//THIS PROGRAM ILLUSTRATES THE USE OF return STATEMENTS AND THE USE OF //LOCAL VARIABLES IN METHODS /* This program calculates the area of a rectangle */ import java.awt.*; import java.applet.Applet; public class RectangleArea extends Applet{ public void paint(Graphics g){ int answer = areaOfRectangle(30,40); //value returned by //areaOfRectangle is //stored in LOCAL //VARIABLE answer g.drawString("Area of rectangle is " + answer, 100, 100); } private int areaOfRectangle(int sideA,int sideB){ int area = sideA * sideB; return area; } }
/*THIS PROGRAM ILLUSTRATES THE USE OF METHODS IN JAVA */ //IT DRAWS A TRIANGLE WITH HORIZONTAL BASE AND TWO SIDES //OF EQUAL LENGTH FROM ITS LEFT AND RIGHT END POINTS //<applet code="TriangleMethod.class" width=300 height=300></applet> import java.awt.*; import java.applet.Applet; public class TriangleMethod extends Applet{ public void paint(Graphics gg){ drawTriangle(gg,80,200,100,110); //METHOD CALL to method //drawTriangle drawTriangle(gg,125,220,60,70); //another METHOD CALL to //method drawTriangle } // This is called the DEFINITION of the drawTriangle METHOD public void drawTriangle(Graphics g, int bottomX, int bottomY, int base, int height){ g.setColor(Color.red); //color of base line g.drawLine(bottomX,bottomY,bottomX+base,bottomY); //draw base line g.setColor(Color.blue); //color of right side of the triangle g.drawLine(bottomX+base,bottomY,bottomX+base/2,bottomY-height);//draw right side g.setColor(Color.black); //color of left side of the triangle g.drawLine(bottomX+base/2,bottomY-height,bottomX,bottomY); //draw left side }// DEFINITION of drawTriangle method ends here }
public void drawTriangle(Graphics g, int bottomX, int bottomY, int base, int height)
Name | |
g | the reference (address) of a Graphics object |
bottomX | an integer value |
bottomY | an integer value |
base | an integer value |
height | an integer value |
Line 12 | drawTriangle(gg,80,200,100,110); Here drawTraingle has five actual parameters namely gg, 80,200, 100, 110. The value contained in gg is copied to the corresponding formal parameter g in lines 20 and 21 during the drawTriangle method call. Also 80, 200,100,110 are copied similarly. |
line 20-21 | public void drawTriangle(Graphics g, int bottomX, int bottomY, int base, int height)
Thus value in gg is passed to formal parameter g value 80 is passed to formal parameter bottomX value 200 is passed to formal parameter bottomY value 100 is passed to formal parameter base value 110 is passed to formal parameter height |
Line 28 | g.drawLine(bottomX+base,bottomY,bottomX+base/2,bottomY-height); Here drawLine method passes four actual parameters to its corresponding actual parameters. Thus the value in bottomX is added to the value in base and the sum is passed as an actual parameter. Similarly value of bottomY is passed value of bottomX + base/2 is passed and value of bottomY - height is passed. |
STANDALONE EXAMPLES
public class ThreeN2 {
/* A program that computes and displays several 3N+1 sequences. Starting values for the sequences are input by the user. Terms in a sequence are printed in columns, with five terms on each line of output. After a sequence has been displayed, the number of terms in that sequence is reported to the user. */
public static void main(String[] args) {
TextIO.putln("This program will print out 3N+1 sequences"); TextIO.putln("for starting values that you specify."); TextIO.putln();
int K; // Starting point for sequence, specified by the user. do { TextIO.putln("Enter a starting value;"); TextIO.put("To end the program, enter 0: "); K = TextIO.getInt(); // get starting value from user if (K > 0) // print sequence, but only if K is > 0 Print3NSequence(K); } while (K > 0); // continue only if K > 0
} // end main()
static void Print3NSequence(int startingValue) {
// Prints a 3N+1 sequence to standard output, using // startingValue as the initial value of N. Terms are // printed five to a line. The subroutine also // prints the number of terms in the sequence. // The value of startingValue must be a positive integer.
int N; // One of the terms in the sequence. int count; // The number of terms found. int onLine; // The number of terms that have been output // so far on the current line.
N = startingValue; // Start the sequence with startingValue; count = 1; // We have one term so far.
TextIO.putln("The 3N+1 sequence starting from " + N); TextIO.putln(); TextIO.put(N, 8); // Print initial term, using 8 characters. onLine = 1; // There's now 1 term on current output line.
while (N > 1) { N = nextN(N); // compute next term count++; // count this term if (onLine == 5) { // If current output line is full TextIO.putln(); // ...then output a carriage return onLine = 0; // ...and note that there are no terms // on the new line. } TextIO.put(N, 8); // Print this term in an 8-char column. onLine++; // Add 1 to the number of terms on this line. }
TextIO.putln(); // end current line of output TextIO.putln(); // and then add a blank line TextIO.putln("There were " + count + " terms in the sequence.");
} // end of Print3NSequence()
static int nextN(int currentN) { // Computes and returns the next term in a 3N+1 sequence, // given that the current term is currentN. if (currentN % 2 == 1) return 3 * currentN + 1; else return currentN / 2; } // end of nextN()
} // end of class ThreeN2
why is static so important?
Declare a class member (fields or methods) which is instantiated only in the class itself (vs. in each instantiated object of that class).
static class <className> { // methods and variables } static <returnType> <methodName> (<params>) { // something useful here } static <variableType> <variableName>;
Declaring a construct global ensures that internally only one copy of that construct will be created. The access to the construct is not affected by static, but rather is outlined by one of the keywords private, protected, and public.
Note that a static method cannot use any instance variables of the class in which it is defined unless they are static instance variables. The advantage to a static method is that an instance of the class does not need to be defined in order to use the method. For example:
double result = Math.sqrt (5);
Math is a class with a static method called sqrt
. We never have to
create an instance of the class Math
in order to use its static methods.
/** * The following will square an integer */ static int Square (int x) { return x*x; } // the following is a constant public static final int WIDTH = 500;
If a class property is also declared final, then it becomes a global constant (i.e. can't be altered):
public class A {
final static int k_var;
....
}
This is how the pi value Math.PI is created in the Math class.
Similarly, methods can also be declared static, and are called class methods
public class A {
static void A_method(float x){...}
....
}
These class methods also can be called even when no instance of the class exists. The code in a class method can only refer to static variables and the argument variables.
The Math class that we have used, for example, contains static methods to carry out various mathematical functions without having to create a Math object.
public class mathExample {
static double pi=3.14;
double b=3;
double func(double x){
return ( 4.0*Math.sin(x)**2);
}
static double sfunc(double x){
return (3.0*x);
}
static double tfunc(double x){
return (3.0*x*pi);
}
static double wfunc(double x){
return (3.0*x*b);=> Error!
Cannot use nonstatic
variable in a class
method.
}
}
assignment
1.In one program write and implement methods for the following:
a--babbage's function f(x)=x*x +x +41 call it static int f(int x)
b--static int min(int x1, int x2 , int x3, int x4)
c--: Write a subroutine that to output 10 lines of stars with 1 star in the first line, 2 stars in the second line, and so on, as shown below.
* ** *** **** ***** ****** ******* ******** ********* **********
d: Write a function named countChars that has a String and a char as parameters. The function should count the number of times the character occurs in the string, and it should return the result as the value of the function.
3. Write an applet which has a method which a circle of any radius in any position. The user will be prompted for the radius and the center of the circle.