3.4. Calling Methods With Parameters¶
In the last lessons, we used simple methods like forward
and turnRight
to make the turtle draw lines. You may have noticed that forward()
and backward()
always move the same number of pixels (100 pixels), and turnRight()
and turnLeft()
always turn at right angles (90 degrees). This is a little limiting. What if we wanted to draw a triangle or the letter A? These require smaller angles to draw diagonal lines and different length lines. Luckily, there are more complex methods in the Turtle
class that let you specify the number of pixels to move forward or the number of degrees to turn. These values that you can give to methods to help them do their job are called arguments or parameters.
The parentheses ()
after method names when we call a method are there in case you need to give the method actual parameters or arguments (some data) to do its job. For example, we can give the argument 100 in forward(100)
to make the turtle go forward 100 pixels or the argument 30 in turn(30)
to make the turtle turn 30 degrees instead of 90 degrees.
Note
object.method(arguments); is used to call an object’s method and give it some arguments (actual parameters) to do its job.
Although some people use the words parameters and arguments interchangeably, there is a subtle difference. When you create your own method, the variables you define for it are called formal parameters. When you call the method to do its job, you give or pass in arguments or actual parameters to it that are then saved in the parameter variables. So, in the definition of the forward
method, it has a parameter variable called pixels
, and in the call to forward(100)
, the argument is the value 100 which will get saved in the parameter variable pixels. You will learn to write your own methods in Unit 5. In this unit, you will learn to call methods that are already written for you.
// Method call
yertle.forward(100); // argument is 100
// Method definition written for you
public void forward(int pixels) // parameter pixels
...
-
2-4-1: Drag the definition from the left and drop it on the correct word on the right. Click the "Check Me" button to see if you are correct.
Review the vocabulary above.
- an object's behaviors or functions that can be used or called to do its job
- methods
- the values or data passed to an object's method
- arguments or actual parameters
- the variables in a method's definition that hold the arguments
- formal parameters
- asking to run the method
- method call
![](../_static/turtleTurnForwardRightForward.png)
The following program uses a turtle to draw the picture shown to the left, but the lines are mixed up. The program should do all necessary set-up: import items, start the class definition, start the main method, and create a world and turtle. Then it should ask the turtle to turn 45 degrees, go forward 100 pixels, turn right, and then go forward 50 pixels. Next, it should ask the world to show itself. Finally, it should close the main method and class definition. We have added a compass to the picture to indicate the directions north, south, west, and east. Drag the needed blocks of statements from the left column to the right column and put them in the right order. There are three extra blocks that are not needed in a correct solution. Then click on Check Me to see if you are right. You will be told if any of the lines are in the wrong order or are the wrong blocks.
Here is the Turtle class diagram again that shows some of the variables and methods inherited from the SimpleTurtle class in the class Turtle that are written for you.
![Turtle class diagram](../_images/turtleUMLClassDiagram.png)
Figure 1: Turtle Class Diagram¶
Try some of the methods above in the turtle code below. You can see all the methods that are inherited in Turtle in this javadoc (documentation) file.
Methods are said to be overloaded when there are multiple methods with the same name but a different method signature, where it requires a different number or type of parameters. For example, we have two different forward methods, forward() with no parameters and forward(100) which has a parameter that tells it how much to move forward. If there is more than one parameter, then the values given to the method need to correspond to the order and types in the method signature.
(If the code below does not work in your browser, you can also use the Turtle code at this replit.com link (refresh page after forking and if it gets stuck) or download the files here to use in your own IDE.)
Can you make yertle draw a square and change the pen color for each side of the square? Try something like: yertle.setColor(Color.red); This uses the Color class in Java which has some colors predefined like red, yellow, blue, magenta, cyan. You can also use more specific methods like setPenColor, setBodyColor, and setShellColor.
Can you draw a triangle? The turnRight() method always does 90 degree turns, but you’ll need external angles of 120 degree for an equilateral triangle. Use the turn method which has a parameter for the angle of the turn in degrees. For example, turn(90) is the same as turnRight(). Try drawing a triangle with different colors.
Try the following mixed up code to draw a simple house made of a square and a triangle roof.
![simple house](../_images/house.png)
The following code uses a turtle to draw a simple house, but the lines are mixed up. Drag the code blocks to the right and put them in the correct order to first draw a square for the house and then a red triangle for the roof. Click on the “Check Me” button to check your solution. You can type this code in the Active Code window above to see it in action.
3.4.1. Tracing Methods¶
You will not write your own methods until Unit 5, but you should be able to trace and interpret method calls like below.
Here is another version of the Old MacDonald Song with a more powerful abstraction. The method verse has 2 parameters for the animal and the noise it makes, so that it can be used for any animal. Use the Code Lens button or this Java visualizer to step through the code.
Add another verse in main that calls the method verse with a different animal and noise.
- 25 and 2
- Correct.
- 25 and .5
- The order of the arguments to the divide(x,y) method will divide x by y and return an int result.
- 2 25
- The square(x) method is called before the divide(x,y) method.
- 25 2
- The main method prints out " and " in between the method calls.
- Nothing, it does not compile.
- Try the code in the visualizer link below.
2-4-6: What does the following code print out?
public class MethodTrace
{
public void square(int x)
{
System.out.print(x * x);
}
public void divide(int x, int y)
{
System.out.println(x / y);
}
public static void main(String[] args)
{
MethodTrace traceObj = new MethodTrace();
traceObj.square(5);
System.out.print(" and ");
traceObj.divide(4, 2);
}
}
Try this visualization to see this code in action.
3.4.2.
Programming Challenge : Turtle House¶
![simple house](../_images/houseWithWindows.png)
This creative challenge is fun to do collaboratively in pairs. Design a house and have the turtle draw it with different colors below (or with this replit.com link). Can you add windows and a door? Come up with your own house design as a team.
To draw a window, you will need to call penUp
to walk the turtle into position, for example:
builder.penUp();
builder.moveTo(120,200);
builder.penDown();
It may help to act out the code pretending you are the turtle. Remember that the angles you turn depend on which direction you are facing, and the turtle begins facing up.
Draw a Turtle House! Make sure you use forward, turn, penUp, penDown, moveTo methods as well as different colors. Have fun!
3.4.3. Summary¶
Methods define the behaviors or functions for objects.
To use an object’s method, you must use the object name and the dot (.) operator followed by the method name, for example object.method();
Some methods take parameters/arguments that are placed inside the parentheses object.method(arguments).
Values provided in the parameter list need to correspond to the order and type in the method signature.
3.4.4. AP Practice¶
inches –> centimeters
-
The values of the variables inches and centimeters should be printed out, not the words.
10 –> 25
-
Two doubles should be printed, not two ints, and the centimeters should be 25.4
25.4 –> 10
-
Inches should be printed before centimeters.
10 –> 12.54
-
c = 10 * 2.54 = 25.4, not 12.54.
10.0 –> 25.4
-
Correct! centimeters = 10 * 2.54 = 25.4.
2-4-8: Consider the following methods:
public void inchesToCentimeters(double i)
{
double c = i * 2.54;
printInCentimeters(i, c);
}
public void printInCentimeters(double inches, double centimeters)
{
System.out.print(inches + "-->" + centimeters);
}
Assume that the method call inchesToCentimeters(10)
appears in a method in the same class. What is printed as a result of the method call?
printSlices(slicesPerPerson);
-
Correct! If you had 4 people, slicesPerPerson would be 8/4=2 and printSlices would print out “Each person gets 2 slices each”.
printSlices(numOfPeople);
-
If you had 4 people, this would print out that they get 4 slices each of an 8 slice pizza.
printSlices(8);
-
This would always print out 8 slices each.
splitPizza(8);
-
This would not call the printSlices method.
splitPizza(slicesPerPerson);
-
This would not call the printSlices method.
2-4-9: Consider the following methods, which appear in the same class.
public void splitPizza(int numOfPeople)
{
int slicesPerPerson = 8/numOfPeople;
/* INSERT CODE HERE */
}
public void printSlices(int slices)
{
System.out.println("Each person gets " + slices + " slices each");
}
Which of the following lines would go into /* INSERT CODE HERE */
in the method splitPizza in order to call the printSlices
method to print the number of slices per person correctly?