Write a program to test your
class. Use integer variables to represent the private instance variables of the class—the numerator and
the denominator. Provide a constructor that enables an object of this class to be initialized when it’s
declared. The constructor should store the fraction in reduced form. The fraction:
2/4 is equivalent to 1/2 and would be stored in the object as 1 in the numerator and 2 in the denominator.
Provide a no-argument constructor with default values in case no initializers are provided. Provide public
methods that perform each of the following operations:
Add two Rational numbers: The result of the addition should be stored in reduced form.
Subtract two Rational numbers: The result of the subtraction should be stored in reduced form.
Multiply two Rational numbers: The result of the multiplication should be stored in reduced
form.
Also, write a test program to test all methods, and provide the UML class diagram of your class.
public class RationalNumber {
private int numerator;
private int denominator;
public RationalNumber() {
this(0, 1);
}
public RationalNumber(int numerator, int denominator) {
int gcd = gcd(numerator, denominator);
this.numerator = numerator / gcd;
this.denominator = denominator / gcd;
}
private static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public RationalNumber add(RationalNumber other) {
int mNumerator = numerator * other.denominator + other.numerator * denominator;
int mDenominator = denominator * other.denominator;
return new RationalNumber(mNumerator, mDenominator);
}
public RationalNumber subtract(RationalNumber other) {
int mNumerator = numerator * other.denominator - other.numerator * denominator;
int mDenominator = denominator * other.denominator;
return new RationalNumber(mNumerator, mDenominator);
}
public RationalNumber multiply(RationalNumber other) {
int mNumerator = numerator * other.numerator;
int mDenominator = denominator * other.denominator;
return new RationalNumber(mNumerator, mDenominator);
}
}
public class Main {
public static void main(String[] args) {
RationalNumber zero = new RationalNumber();
RationalNumber half = new RationalNumber(2, 4);
half.add(zero);
half.multiply(zero);
half.subtract(zero);
}
}
Comments
Leave a comment