|
Spring Semester 2003 |
Next, we can discuss methods. (
Please also check
next week's lab now).
Methods are like recipes. They are generalized formulas.
Here's a recipe, that a human cook could (and might) use:
Mikey's Garlic Mashed Potatoes
Next, we rewrite this recipe for a computer chef. Note the change of attitude.
Mikey's GMP
(In which the cook needs all the help that he can get!)
Note to the customer:
If you want GMP better bring your own ingredients!Chef:
Also, when you pass them to the cook pass them in the right order, and one by one.
Check ingredients carefully, one by one.A few more considerations.
If something doesn't match print error message and stop.The necessary ingredients should be:
- one baking potato (call it
p1)- another baking potato (call it
p2)- some butter (call it
b)- some whipping cream (call it
w)- garlic (call it
g)- cream cheese (call it
cc)- chives (call it
ch)- salt (call it
s)- pepper (call it
p)Start cooking:
- wash
p1.- peel
p1.- quarter
p1and callqp1the result.- wash
p2.- peel
p2.- quarter
p2and callqp2the result.- get recipient (
rec) and some water (wat).- put
wat,s,qp1andqp2inrec.- identify free burner
bu.- put
reconbuand turnbuon.while(qp1not fork tender andqp2not fork tender) {
wait 1 minute patiently
}- drain water out of
recand callbpwhat's left.- identify masher
m1and take it.- mash
bpwithm1, callbpmthe result.- take saucepan
sp.- divide
ccinto two halves:cc1andcc2.- add
cc1andbtosp.- look at watch, record time
now.- compute
thenthe time after one minute- start simmering
while( current time less thanthen) {
stir
wait 2 seconds
}- add
bmpto saucepansp- locate spoon
spoonand stir with it insp- add
cc1to saucepansp- stir with
spooninsp- add
gtospand stir withspoon- turn burner
burneroff- place contents of
spinto plateplateand call itgmp- place
chon top ofgmpand call itgmp:gmp += ch;gmp = gmp + s(add salt)- return
gmp
class Mikey {
public static GarlicMashedPotatoes // this is the return type!
recipeOne( Potato p1,
Potato p2,
Butter b,
WhippingCream w,
Garlic g,
CreamCheese c,
Chives ch,
Salt s,
Pepper p) {
// see the steps detailed above
...
}
Testing the chef. We set up the following situation:
class TestingTheChef {
public static void main(String[] args) {
// first get all the ingredients the chef needs
Potato myPotato1 = new Potato();
Potato myPotato2 = new Potato();
Butter myButter = new Butter(0.5);
...
Pepper myPepper = new Pepper();
GarlicMashedPotatoes result; // get ready with a local plate
result = Mikey.recipeOne(myPotato1, myPotato2, myButter, ..., myPepper);
}
}
Now compile and run the classes.
Bring your own plate to store the result. Note:
A201/A597
LAB ASSIGNMENT EIGHT
Objective Develop a collection of commonly used methods.
Discussion In this lab you will be building up a small library of
methods that we may find useful at some later time. A little time spent now,
carefully considering how these methods ought to be written, can save
considerable amounts of time later when code reuse can be employed.
While we will not always know the context in which a method will be used,
we can generally make a reasonable guess. Whenever possible, we should try
to make the implementation of a method as general as possible. This includes:
If you were to run the following tests
So the description here will be a bit more general.
Inputs:
Also, the problem doesn't say if the output includes
Method:
This value can be looked at as a percentage.
The length of the target interval is
How do you solve this problem? Here's a picture:
Here's an implementation:
When we create a method we follow these steps:
The section above removes all mistery about it, but here's the overview anyway:
Inputs:
Inputs:
Method:
Again, we need to give it a name, code it in Java, place it in the
Inputs:
Inputs:
So these are the recipes. Your
What
comes next is:
LabEight. The six problems are
listed below. For each problem there is a hint, or a bit of advice. For
each problem you are encouraged to think of it as if it were Mikey's GMP
recipe. Here now are the problems, followed by individual hints and pieces
of advice.
Task For each of the following functions and procedures (collectively
known as methods in Java), write the method, and test it thoroughly
before going on.
Assume the following types:
low
and high, inclusive. low and high. Points. Points. Circles overlap. Rectangles overlap.
Here's a sample test of the methods, when you have them ready.class Point {
double x, y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
public String toString() {
return "I am a Point at (" + x + ", " + y + ")";
}
}
class Circle {
private double radius, x, y;
Circle(double r, double x, double y) {
radius = r;
this.x = x;
this.y = y;
}
Point center() {
return new Point(this.x, this.y);
}
double radius() {
return radius;
}
}
class Rectangle {
double x, y, width, height;
Rectangle(double x, double y, double width, double height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
You should obtain an output similar to this:
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
System.out.println(LabEight.random(-14, -8));
for (int i = 0; i < 10; i++)
System.out.println(LabEight.random(3.2, 3.9));
Point p1 = new Point(1, 4);
Point p2 = new Point(5, 1);
System.out.println(LabEight.distance(p1, p2));
Point p3 = LabEight.midpoint(p1, p2);
System.out.println(p3);
Circle c1 = new Circle(10, 3, 3);
Circle c2 = new Circle( 9, 3, 21);
System.out.println(
"Circles overlap? The answer is: " + LabEight.overlaps(c1, c2));
Rectangle r1 = new Rectangle(5, 5, 5, 5);
Rectangle r2 = new Rectangle(7, 1, 2, 2);
System.out.println(
"Rectangles overlap? The answer is: " + LabEight.overlaps(r1, r2));
}frilled.cs.indiana.edu%java LabEight
-13
-9
-10
-14
-8
-13
-12
-13
-8
-14
3.8893441296921716
3.8197796997135343
3.7198162871052696
3.5426342839050067
3.723866363497135
3.8542103463665556
3.762537621124611
3.862830975636286
3.397977654009052
3.2720480907723437
5.0
I am a Point at (3.0, 2.5)
Circles overlap? The answer is: true
Rectangles overlap? The answer is: false
frilled.cs.indiana.edu%
1. We go through three stages:
Inputs:
Outputs: low representing the lower endpoint of the interval
high representing the higher endpoint of the interval
Method: low and high inclusive
First compute the number of possible outcomes in the interval:
Code this in Java and place it in your class
Then obtain a random number between 0 and 1. int num = (high - low + 1);
Scale this number to the interval we're working with. double per = Math.random();
Translate the value into the desired range and return it. int val = (int) (per * num);
return (val + low);
LabEight. Then
in another class, which has the main method, invoke the method
a few times (did you give it a name already?) to test it. You can, in fact,
place the main in LabEight as well (which is what I did). Also,
please note that you may have to adjust the size of the range if you want
to include high as a possible outcome. Or maybe not.
2. This problem is very much related to the previous one.
Outputs: low representing the lower endpoint of the interval
high representing the higher endpoint of the interval
Note: by floating point we mean low and high
float or double, whichever suits you best. high or not,
so this is up to you.
It depends how you're generating the
random numbers but most likely they will
be random numbers between
Now code this in Java, give it a name, place it in 0 and 1, let's call
it val.
so if we want to translate (high - low)
val into a location on the
segment from low to high we will have to
multiply the length of the interval by the percentage:
This is a number that represents a fraction of the length of the target interval
between val * (high - low)
low and high. If we add low to this
we will obtain the desired random number that corresponds to val and
falls in between low and high and we could return it:
As we said it depends on the source you're using. The book says there are two such
sources that you could use: return val * (high - low) + low;
Math.random or a Random object
which could return nextFloat(). In both cases the method described here
would work.
LabEight
and call it a few times from the main
of the other class (or LabEight's itself) to test it,
just to make sure everything is OK.
3. Again, you are being asked to turn a solution in a procedure. How
do you proceed. First solve the problem by itself, at least once. Then turn
your solution into a procedure by looking at what's general in your solution.
Here we need to compute the distance between two points.
Then we isolate the part that calculate the distance and place it in a method. public class Test {
public static void main(String[] args) {
Point p, q;
p = new Point(2, 4);
q = new Point(6, 1);
double distance;
int h, v;
h = Math.abs(p.x() - q.x());
v = Math.abs(p.y() - q.y());
distance = Math.sqrt(h * h + v * v);
System.out.println(distance);
}
} public class Test {
public static void main(String[] args) {
Point p, q;
p = new Point(2, 4);
q = new Point(6, 1);
double distance;
distance = LabEight.computeDistanceBetween(p, q);
System.out.println(distance);
}
}
class LabEight {
public static double computeDistanceBetween(Point p, Point q) {
int h, v;
h = Math.abs(p.x() - q.x());
v = Math.abs(p.y() - q.y());
return Math.sqrt(h * h + v * v);
}
}
Note that the code above assumes Point has
two accessors, for the coordinates. If you don't implement them (and
the class I provided does not have them, but they are easy to write
so you can make the change yourself) then simply remove the parens,
to work directly with the variables. It's up to you. Encapsulation is
not the central point here, when we look at the distance
method. But the preferred method would indeed be to have
accessors with private instance variables (in general).
We've done this in
Test.javaOur
procedure needs the two points. It should have as the result the distance between the two points,
most likely a number with decimals.
We call the parameters, the two points,
p
and q.
Their type is Point. We
decided to call it
computeDistanceBetween. Other names
are possible. void (that is, as not returning a result).
Our method returns a
double.
Outputs: Point p
Point q
Method: p and q
Compute the distances between the points on the horizontal and
on the vertical. Square each on of them, add them up and return the square root of the
result. That is the distance between the two points by
Pythagoras' theorem.
http://www-groups.dcs.st-andrews.ac.uk/~history/Mathematicians/Pythagoras.html
4. I will only provide the formula here and we can discuss this
in class or during office hours.
Outputs: Point p
Point q
Point that is the midpoint of the segment from p to q
How
similar this is with add defined as an instance method in
Fraction! Create a new
Point whose coordinates are the
averages of the coordinates of p and q and return it.One can achieve thist in just one line:
return new Point((p.x() + q.x())/2, (p.y() + q.y())/2);
Same
comment as above about using accessors vs. accessing the variables directly.
LabEight class of methods and invoke it from main
a few times for testing purposes.
5. Read Exercise R7.5 in the text to see
what a predicate means.
Outputs: Circle c1
Circle c2
Method: boolean value telling whether the circles overlap or not
It should be clear that two circles overlap
if and only if the distance between their
centers is smaller than the sum of the two radii. The question is how
do we get the center and the radius out of a
Circle. You
should be able to figure that out. So this method could
also be described in one line (although a long one):
return ( LabEight.distance(c1.center(), c2.center())
<=
c1.radius() + c2.radius());
Same
comment as above about using accessors vs. accessing the variables directly.
So we use the method developed for problem 3.
Name it, code it, place it in LabEight use it a few times
from main to test it.
6. Interesting problem with more than one solution.
Outputs: Rectangle r1
Rectangle r2
Method One: boolean value that
reflects the truth value of the following
assertion:
the two rectangles overlap each other (true or false)
As in the case of circles we need to work with the distance between the
two possibly overlapping entities. Two rectangles overlap when the distance
between their two centers on the horizontal is less than half of their combined
widths and the distance between their two centers on the vertical is less than
half of their combined heights.
Method Two:
The idea here is to realize that
Choose a method, code it in, place it in r1 does not overlap
r2 if r1 is entirely to the north of r2 or
entirely to the east of r2 or entirely to the south of r2
or entirely to the west of r2. (We have thus described the outside
of r2). So now we need to return the negation of this, whatever truth value
it may have. LabEight, test it.
I used Method Two.
main method should be using them to cook a banquet.
Last updated: Mar 9, 2003 by Adrian German for A201