Espresso: A Concentrated Introduction to Java
Summary: In this laboratory, you will explore some of the standard methods by adding them to existing classes.
Primary Classes Used:
Source Files:
Contents
In this lab, you will continue to use the Code project
and the username.fractions package.
a. As always, start Eclipse.
b. If you've configured Fraction so that it automatically
simplifies fractions when they are constructed, remove the code to do
so.
a. In your main class, create a Fraction of your
choice and print it out. What happens?
b. The Fraction class comes with a toString
method. Remove it.
c. Run your main class again. What happens? You've now seen the default
toString method.
d. Reinsert the toString method.
a. In your main class, create the fractions fourThirds
and oneThird with the natural value for each. For
example,
Fraction fourThirds = new Fraction(4,3); Fraction oneThird = new Fraction(1,3);
b. Determine whether or not the fractional portion of fourThirds
is the same as oneThird. For example,
if (fourThirds.fractional().equals(oneThird)) {
pen.println("The fractional portion of " + fourThirds
+ " equals " + oneThird);
}
else {
pen.println("The fractional portion of " + fourThirds
+ " does not equal " + oneThird);
}
c. Write an equals method that indicates that two
fractions are equal if their numerators are the same and their
denominators are the same.
d. Verify that the code from step b now indicates that the two fractions are equal.
a. Extend your main class to create two fractions, oneHalf
and one, with the obvious values.
b. Write code that determines whether oneHalf.add(oneHalf)
is equal to one. (Hint: If you followed instructions above,
it should not be.)
c. Fix the equals method so that it considers the two
equal. Note that you may not use gcd or
simplify in determining equality.
d. Test your change using the code from step b.
a. Write a compareTo(Fraction other) method for your
Fraction class.
b. Test your compareTo method with each of the following pairs
oneHalf.add(oneHalf) and one
c. Correct your method if you identified any errors above.
Write and test a hashCode method for the
Fraction class.
Write and test the clone method for the
Fraction class.
Wednesday, 22 February 2006 [Samuel A. Rebelsky]
Sunday, 26 February 2006 [Samuel A. Rebelsky]
Monday, 27 February 2006 [Samuel A. Rebelsky]
This page was generated by
Siteweaver on Thu Mar 30 15:24:42 2006.
The source to the page was last modified on Mon Feb 27 08:47:50 2006.
This page may be found at http://www.cs.grinnell.edu/~rebelsky/Espresso/Labs/standard-methods.html.
You may wish to
validate this page's HTML
;
;
Check with Bobby