Answer to Question #302178 in Java | JSP | JSF for jeffy

Question #302178

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.


1
Expert's answer
2022-02-24T17:13:06-0500
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);
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS