For this assignment, you should write a class called Fraction
, for storing and manipulating fractions with integer numerators and denominators. Fractions need to have two variables for the numerator and the denominator. Your fraction class also needs to have two methods: one for printing the fraction to the screen and one for multiplying one fraction by another. Lastly, you need to have two different constructors, one which takes a numerator and a denominator to define a new fraction, and one which just takes a single integer (assuming that the denominator is 1). Don't worry about converting things to lowest terms unless you're going for extra credit.
In order to keep everyone's naming scheme, I've included a simple Java tester class called FractionTest
and a sample output. Your job is just to implement the Fraction
class so that the output matches* what I gave.
Here's the tester class:
public class FractionTest {
public static void main(String args[]) {
Fraction twoThirds = new Fraction(2,3);
Fraction five = new Fraction(5);
System.out.print("Two thirds is ");
twoThirds.display();
System.out.print("Five is ");
five.display();
Fraction product = twoThirds.times(five);
System.out.print("Two thirds times five is ");
product.display();
}
}
And here's what the output should look like:
Two thirds is 2/3
Five is 5/1
Two thirds times five is 10/3
*Note to smart alecks: It would be pretty easy just to hard code in the correct answers for this tester (for example, you could just make sure that times()
always returns 10/3). Don't do that. Your class needs to handle arbitrary fractions. If I change up the numbers in the tester class, it still needs to give the right output.
When you've completed the assignment, make sure that the files containing the source code have read permissions set for everyone, and that the compiled classes file have read and execute permissions set for everyone. Then send an e-mail to me and Karteek (our e-mail addresses are on the syllabus) including the paths and the filenames for the source code and the compiled files. To make it easier for us to grade, please make sure that there's a compiled version of the tester (FractionTest.class
) there as well, and make sure everyone has read and execute permissions for it.
If you want some extra credit, add the methods plus()
to add two fractions together and equals
to test if two fractions are equal. Hint: you may want to implement a greatest common divisor function for integers first.
This assignment is due Thursday, July 17th before class.