5.2 Parameters
To make methods more flexible we need to have a way to send information into them. For instance, the sqrt method needs to know which number you want to find the square root of. This is accomplished by using parameters. Suppose we wanted to make a method called circle that will draw a circle. We would need to know the coordinates of the centre and the radius in order to draw it. We would use parameters for that information. Here is a program that will define a circle method and call it three times to draw three different circles.
void circle(int x, int y, int r)
{
ellipse(x, y, r*2, r*2);
}
void setup()
{
size(300, 300);
circle(50, 50, 25);
circle(125, 50, 50);
circle(125, 200, 100);
}
|
|
The method call circle(125, 200, 100); above passes three arguments to the three parameters in the definition of the circle method. 125 gets stored in the parameter x, 200 gets stored in y and 100 gets stored in r.
It important that the number of arguments matches the number of parameters. You also need to make sure that the types match properly. Suppose you had a method whose heading was:
void doSomething(float f, char c)
Suppose that you had the following declarations:
int a = 10;
char letter = 'm';
float x = 2.5;
Consider the following calls:
doSomething(x); // illegal, too few arguments
doSomething(x, letter); // legal
doSomething(a, 'z'); // legal, a will get widened to a float
doSomething(a + 5, letter); // legal, a + 10 will be evaluated (10 + 5 = 15) and that value gets passed to f
doSomething(letter, x); // illegal, x is a float and a float can't be stored in a char
doSomething(x, letter, "too Many"); // illegal, too many arguments
Exercise 5.2
- A student wrote the following method to exchange the values of two int variables.
void swap (int m, int n)
{
int temp = m;
m = n;
n = temp;
}
He then tested the method with the following fragment:
i = 7;
j = 3;
swap(i,j);
println("i = " + i + " and j = " + j);
What did the fragment print? Explain.
- Suppose a method has the following heading:
void doThis(int n, float x)
State which of the following calls are invalid. Justify your answer in each case.
- doThis(0.5, 2);
- doThis(3, 4);
- doThis(2.0, 1.5);
|
- doThis(-2, 8.0);
- doThis('x', 5);
- doThis(3L, 4);
|
- Write the defintion of a method called square. This method will take three parameters. It should draw a square at the coordinates specified by the first two parameters. The lengths of the sides should be specified by the third parameter.
-
- Complete the definition of the method printRect so that it prints a filled rectangular pattern, using the character c, that is w characters wide and h characters high.
void printRect(char c, int w, int h)
- Modify your method so that it prints an open rectangular pattern with blanks in the interior (if there is one).
| |