Answer to Question #302365 in Java | JSP | JSF for fara

Question #302365

Create a class called Rational for performing arithmetic with fractions. 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.


1
Expert's answer
2022-02-24T12:17:45-0500





class Rational {
	private int num; // the numerator
	private int den; // the denominator


	// create and initialize a new Rational object
	public Rational(int numerator, int denominator) {
		if (denominator == 0) {
			throw new RuntimeException("Denominator is zero");
		}
		int g = gcd(numerator, denominator);
		num = numerator / g;
		den = denominator / g;


	}


	public String toString() {
		if (den == 1)
			return num + "";
		else
			return num + "/" + den;
	}


	// return (this * b)
	public Rational multiplication(Rational b) {
		return new Rational(this.num * b.num, this.den * b.den);
	}


	// return (this + b)
	public Rational addition(Rational b) {
		int numerator = (this.num * b.den) + (this.den * b.num);
		int denominator = this.den * b.den;
		return new Rational(numerator, denominator);
	}


	// return (this - b)
	public Rational subtraction(Rational b) {
		int numerator = (this.num * b.den) - (this.den * b.num);
		int denominator = this.den * b.den;
		return new Rational(numerator, denominator);
	}


	// return (1 / this)
	public Rational reciprocal() {
		return new Rational(den, num);
	}


	// return (this / b)
	public Rational division(Rational b) {
		return this.multiplication(b.reciprocal());
	}


	// return gcd(m, n)
	private static int gcd(int m, int n) {
		if (0 == n)
			return m;
		else
			return gcd(n, m % n);
	}
}


class App {


	public static void main(String[] args) {
		Rational x, y, z;


		// 1/2 + 1/3 = 5/6
		x = new Rational(1, 2);
		y = new Rational(1, 3);
		z = x.addition(y);
		System.out.println("1/2 + 1/3 = " + z);


		// 8/9 + 1/9 = 1
		x = new Rational(8, 9);
		y = new Rational(1, 9);
		z = x.addition(y);
		System.out.println("8/9 + 1/9 = " + z);


		// 8/9 - 1/9 = 7/9
		x = new Rational(8, 9);
		y = new Rational(1, 9);
		z = x.subtraction(y);
		System.out.println("8/9 - 1/9 = " + z);


		// 4/17 * 7/3 = 28/51
		x = new Rational(4, 17);
		y = new Rational(7, 3);
		z = x.multiplication(y);
		System.out.println("4/17 * 7/3 = " + z);


		// 203/16957 * 9299/5887 = 17/899
		x = new Rational(203, 16957);
		y = new Rational(9299, 5887);
		z = x.multiplication(y);
		System.out.println("203/16957 * 9299/5887 = " + z);


		// 0/6 = 0
		x = new Rational(0, 6);
		System.out.println("0/6 = " + x);


	}
}

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