Void methods

advertisement
Week 8 - Wednesday


What did we talk about last time?
StdDraw

The following methods can be used to draw
lines and points
Method
Use
void line(double x0, double y0,
double x1, double y1)
Draw a line from (x0,y0)
to (x1,y1)
void point(double x, double y)
Draw a point at (x,y)

Here are some methods for drawing circles and
squares and setting the color for doing so:
Method
Use
void circle(double x, double y,
double r)
Draw a circle centered at
(x,y) with radius r
void filledCircle(double x,
double y, double r)
Draw a filled circle centered
at (x,y) with radius r
void square(double x, double y,
double r)
Draw a square centered at
(x,y) with edges 2r
void filledSquare(double x,
double y, double r)
Draw a filled square centered
at (x,y) with edges 2r
void setPenColor(Color c)
Start drawing with color c

A number of methods are given to give us
more control over the display
Method
Use
void setXscale(double x0, double x1)
Set the x scale
void setYscale(double y0, double y1)
Set the y scale
void setPenRadius(double r)
Set the pen radius
void setCanvasSize(int w, int h)
Set canvas size
void clear()
Clear canvas to white
void clear(Color c)
Clear canvas to color c
void show(int delay)
Delay for delay ms







Can we simulate a cannon being fired?
Let the user enter an initial velocity in m/s
Let the user an angle between 0° and 90°
Assume each iteration takes 1/10 of a second
Assume an initial height of 20 m
We draw the path of the cannon ball as it flies
through the air
Let’s also set the x and y scales to both be
[0,100]



Plotting functions is really useful
Getting smooth curves is hard
Instead, we just pick a whole bunch of x
points and figure out the function value
 We can just draw dots to plot those values
 We can connect them with lines for a more
connected look

Let’s write some code to draw cubic
polynomials
1.
2.
3.
4.
5.
Ask the user for the coefficients of the four
terms (ax3 + bx2 + cx + d)
Ask the user for an x range
Run through the function and find the
minimum and maximum y values hit
Rescale the drawing area to show
everything
Plot the function





We have written lots of code so far
It has all been inside of the main() method
What about a big program?
The main() method is going to get really long
and hard to read
Sometimes you need to do similar things several
times:
 Read some input and check that it falls within certain
values
 Draw a green hexagon at several different locations
 Find the square root of several different numbers




Methods allow you to package up some code
to run over and over
Methods usually take some input (like
numbers or Strings) so that they can be
customized
Methods often give back an answer (like the
square root of a number)
Also called functions in some other
languages

More modular programming
 Break a program into separate tasks
 Each task could be assigned to a different
programmer

Code reusability
 Use code over and over
 Even from other programs (like Math.sqrt())
 Less code duplication

Improved readability
 Each method can do a few, clear tasks
Required syntax Type of
answer
Type of
1st argument
Type of
last argument
public static type name(type arg1,…,type argn)
{
statement1;
Name of
Name of
statement2;
1st argument
last argument
…
statementm;
}
Name of method
Code done by method

Given two integers, find the smaller:
public static int min(int a, int b)
{
if( a < b )
return a;
else
return b;
}




static methods are methods that are not
connected to a particular object
They are just supposed to perform some
simple task
We are going to focus on static methods
until next week
For now, just taken it as a given that the
definition of every method will include the
static keyword

It is possible to divide methods into two
types:
 Value returning methods
 Void methods

Value returning methods give an answer:
int small = min(x, y);

Void methods are declared with void as their
return type
public static void help(int times) {
for( int i = 0; i < times; i++ )
System.out.println("Help!");
}


Void methods just do something
If you try to save the value they give back, there
will be a compiler error





Like most code in Java, the code inside of a
method executes line by line
Of course, you are allowed to put if
statements and loops inside methods
You can also put in return statements
A method will stop executing and jump back
to wherever it was called from when it hits a
return
The return statement is where you put the
value that will be given back to the caller




Defining a method is only half the game
You have to call methods to use them
Calling a method means giving a method the
parameters (or arguments) it needs and then
waiting for its answer
By now, you have done many method calls
 System.out.println()
 Math.sqrt()

You can call your own methods the same way

Proper syntax for calling a static method
gives first the name of the class that the
method is in, a dot, the name of the method,
then the arguments
Class.name(arg1, arg2, arg3);


If the method is in the same class as the code
calling it, you can leave off the Class. part
If it is a value returning method, you can store
that value into a variable of the right type

Variables from outside of the method don’t
exist unless they have been passed in as
parameters
public static int add(int x, int y){
int z = x + y;
return z;
}

No matter how complex a program is, inside
this method, only x, y, and z variables exist




A magical process called binding happens
which copies the values from the calling code
into the parameters of the method
The calling code can use variables with the
same names, with different names, or even
just literals
The method does not change the values of
the variables in the original code
Remember, it only has copies of the values
int a = 10;
int x = 3;
int y = add( 5, a );
//y contains 15 now
public static int add(int x, int y){
int z = x + y; //5 + 10
return z;
}

No connection between the two different x’s
and y’s
1.
2.
3.
4.
5.
6.
Start a method with the keywords public
static
Next comes the return type
Then the name of the method
Then, in parentheses, the arguments you
want to give to the method
Inside braces, put the body of the method
Include a return statement that gives
back a value if needed



Keep reading Chapter 8
More method practice
Lab 8


Keep reading Chapter 8 of the textbook
Keep working on Project 3
 Due next Friday
Download