Method Calls and Arguments
Methods exist for us to use. A method call is a statement in your program code that tells the computer to run a particular method, and wait for it to complete before moving to the next instruction. When you call a method, you use its name and then provide a list of values between parenthesis. These values are called arguments, they give data to the method for it to use in its actions.
Example
The following code demonstrates several method calls. Notice how each is always the name of the method, followed by 0 or more values within parenthesis. When the method returns data, we can store that in a variable or use it to pass as the value to another method.
Activities
How many method calls and how many arguments does each method have?
WriteLine("Hello World");
OpenWidow("Test", 1920, 1080);
int weight = (start + 10) * 2;
int age = ToInt32(line);
DrawLine(RandomColor(), x1, y1, Rnd(100), Rnd(100));
int width = Rnd(ToInt32(ReadLine()));
Note: Rnd
is a method that generates a random number.
Answers
- 1: This has one method call to
WriteLine
with a single string argument. - 2: This has one method call to
OpenWindow
with three arguments: a string and two numbers. - 3: This does not have any method calls.
- 4: This has one method call to
ToInt32
, which is passed one argument. - 5: There are four method calls on this line.
DrawLine
,RandomColor
, and two calls toRnd
.DrawLine
is passed five arguments,RandomColor
none, andRnd
is passed one. - 6: There are three method calls:
Rnd
,ToInt32
, andReadLine
.ReadLine
runs first and is passed no arguments. BothRnd
andToInt32
are passed one argument. The result ofReadLine
is passed toToInt32
. The result ofToInt32
is then passed intoRnd
.