Synopsis
This class introduced us to the command and operator and what they are and why you use one or the other. Examples in their use are shown as well.
|
Definition
A COMMAND is a program that performs an action other than returing a value.
Definition
An OPERATOR is a program that returns a value.
Ex:
In the context of a the Circle class.
area () is an operator.
shrink () is a command.
Ex:
In the context of the IO class...
println (< int >) is a command.
read_int () is an operator.
Example operator definition.
The operator computes the real average of two integers.
Definition of average:
static public double average (int x, int y)
{
int sum = x + y;
double average = sum / 2.0;
return average;
}
|
Using the operator...
Application: double a = average (2, 5); = 3.5
The execution of average (2, 5)
- Parameters are ``passed''. This means bindings are established from the ``formal parameters'' in the definition to the ``actual parameters'' in the applicaiton.
x - > 2
y - > 5
- The body of the method is executed in the context of the parametric bindings.
sum - > 7
average - > 3.5 (the value returned).
Here is what we use it for...
Problem
Read two real numbers. Interpret the first of the radius of a circle, and the second as the side of a square. Display the average value of the areas of the corresponding circle and square.
class averageCS
{
static public void main (---)
double r = IO.read_double ();
double r = IO.read_double ();
double acs = averageCS (r, s);
IO.println ( ``The average area is ``+ acs + ``square inches'');
}
static private double averageCS (double radius, double side)
{
/ /create the circle
Circle c = new Circle (radius);
Square s = new Square (side);
double ave = (c.area () + s.area () / 2.0;
return ave;
}
}
|
The ``block structure'' of this application
----------------------------------------
| averageCS |
| ------------------------------------ |
| | main () main | |
| | | |
| ------------------------------------ |
| | average () operator | |
| | | |
| ------------------------------------ |
--------------------------------------- |
Notes on the execution....
Suppose 10.0 and 20.0 are numbers which will be read.
in main (): r - > 10.0
in main (): s - > 20.0
``in'' averageCS (---):
radius - > 10.0
side - > 20.0
in averageCS (---):
c - > (circle) of 10.0 radius
s - > (square) of 20.0 side length
ave - > 357. ? < - value returned to the main method.
in main ():
acs - > 357. ? - the value is displayed
Example of a
command
definition:
Command which takes one integer and displays both the predecessor & the successor.
~ ~ ~ = stuff
~ ~ ~ void < - indicates no value will be returned
~ ~ ~ void printPS (int x)
{
IO.println (x-1);
IO.println (x + 1);
}
|
Example Use
~ ~ ~ main (--)
{
printPS (5);
printPS (10);
}
|
Output Stream
4 6 9 11
Lab was discussed today as well.