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
p1
and callqp1
the result.- wash
p2
.- peel
p2
.- quarter
p2
and callqp2
the result.- get recipient (
rec
) and some water (wat
).- put
wat
,s
,qp1
andqp2
inrec
.- identify free burner
bu
.- put
rec
onbu
and turnbu
on.while
(qp1
not fork tender andqp2
not fork tender) {
wait 1 minute patiently
}- drain water out of
rec
and callbp
what's left.- identify masher
m1
and take it.- mash
bp
withm1
, callbpm
the result.- take saucepan
sp
.- divide
cc
into two halves:cc1
andcc2
.- add
cc1
andb
tosp
.- look at watch, record time
now
.- compute
then
the time after one minute- start simmering
while
( current time less thanthen
) {
stir
wait 2 seconds
}- add
bmp
to saucepansp
- locate spoon
spoon
and stir with it insp
- add
cc1
to saucepansp
- stir with
spoon
insp
- add
g
tosp
and stir withspoon
- turn burner
burner
off- place contents of
sp
into plateplate
and call itgmp
- place
ch
on top ofgmp
and call itgmp
:gmp += ch;gmp = gmp + s
(add salt)- return
gmp
Testing the chef.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 ... }
We set up the following situation:
Now compile and run the classes. Bring your own plate to store theclass 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); } }
result
. Note:
A201/A597 LAB ASSIGNMENT EIGHT
You are to build a small library of six methods. These methods will be all grouped in a class calledLabEight
. 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. 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:
low
and high
, inclusive.
low
and high
.
Point
s.
Point
s.
Circle
s overlap.
Rectangle
s 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; } }
If you were to run the following tests
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:
low
representing the lower endpoint of the interval
high
representing the higher endpoint of the interval
low
and high
inclusive
First compute the number of possible outcomes in the interval:Code this in Java and place it in your classThen 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.
So the description here will be a bit more general.
Inputs:
low
representing the lower endpoint of the interval
high
representing the higher endpoint of the interval
low
and high
float
or double
, whichever suits you best.
Also, the problem doesn't say if the output includes high
or not,
so this is up to you.
Method:
It depends how you're generating the random numbers but most likely they will be random numbers betweenNow code this in Java, give it a name, place it in0
and1
, let's call itval
.This value can be looked at as a percentage.
The length of the target interval is
so if we want to translate(high - low)val
into a location on the segment fromlow
tohigh
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 betweenval * (high - low)low
andhigh
. If we addlow
to this we will obtain the desired random number that corresponds toval
and falls in betweenlow
andhigh
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 aRandom
object which could returnnextFloat()
. 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.
How do you solve this problem? Here's a picture:
Here's an implementation:
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).
When we create a method we follow these steps:
We've done this in Test.java
Our 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
andq
. Their type isPoint
.
We
decided to call it computeDistanceBetween
. Other names
are possible.
void
(that is, as not returning a result).
Our method returns a double
.
The section above removes all mistery about it, but here's the overview anyway:
Inputs:
Point p
Point q
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.
Inputs:
Point p
Point q
Point
that is the midpoint of the segment from p
to q
add
defined as an instance method in
Fraction
! Method:
Create a newPoint
whose coordinates are the averages of the coordinates ofp
andq
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.
Again, we need to give it a name, code it in Java, place it in the
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.
Inputs:
Circle c1
Circle c2
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 aSame comment as above about using accessors vs. accessing the variables directly.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());
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.
Inputs:
Rectangle r1
Rectangle r2
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 thatChoose a method, code it in, place it inr1
does not overlapr2
ifr1
is entirely to the north ofr2
or entirely to the east ofr2
or entirely to the south ofr2
or entirely to the west ofr2
. (We have thus described the outside ofr2
). So now we need to return the negation of this, whatever truth value it may have.
LabEight
, test it.
I used Method Two.
So these are the recipes.
Your main
method should be using them to cook a banquet.