In this lab, you'll expand upon the Fraction
class that you wrote for yesterday's homework assignment. First, you should create a dividedby()
method to divide two fractions. If the argument fraction has a numerator of zero, the method should throw
an exception (an ArithmeticException
, with the exception message "Divide by zero" to be precise). You should also add a toString()
method, which will return a string representing the fraction (so if the numerator is 4 and the denominator is 7, then it would return "4/7"). Lastly, you should create a method called displayQuotients()
that takes an array of Fractions
as an argument (to be used as divisors) and divides the fraction by each of the divisors, displaying the answer. If one of those fractions happens to be zero, resulting in an ArithmeticException
, then your method should catch
that exception and display the message "Can't divide by zero; skipping to the next divisor..." before moving on to the next divisor.
As before, I'm providing you with a tester class and a desired output. If your output is off very slightly (like if the spacing is slightly different, or you spelled a word differently, or used slightly different phrasing), that's okay. Here is the tester class:
public class FractionTest {
public static void main(String args[]) {
Fraction twoThirds = new Fraction(2,3);
Fraction five = new Fraction(5);
Fraction zero = new Fraction(0);
Fraction[] divisors = {twoThirds, zero, five};
System.out.println("Two thirds is " + twoThirds);
System.out.println("Five is " + five);
System.out.println("Zerp is " + zero);
Fraction product = twoThirds.times(five);
System.out.println("Two thirds times five is " + product);
Fraction quotient1 = five.dividedby(twoThirds);
System.out.println("Five divided by two thirds is " + quotient1);
twoThirds.displayQuotients(divisors);
Fraction quotient2 = twoThirds.dividedby(zero);
System.out.println("Two thirds divided by zero is " + quotient2);
}
}
And here is the desired output:
Two thirds is 2/3
Five is 5/1
Zerp is 0/1
Two thirds times five is 10/3
Five divided by two thirds is 15/2
2/3 divided by 2/3 is 6/6
Can't divide by zero; skipping to the next divisor...
2/3 divided by 5/1 is 2/15
Exception in thread "main" java.lang.ArithmeticException: Divide by zero
at Fraction.dividedby(Fraction.java:32)
at FractionTest.main(FractionTest.java:22)
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 get one of the AI's to check that everything is completed properly or 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.
This assignment is due Monday, July 21st before class.
If you need some help with exceptions or arrays, check out these links