Ads

Rational numbers are numbers that can be represented as a fraction p / q where p is an integer number and q is a positive integer (q != 0). Design and implement a Java class RationalNumber for representing such numbers. Implement methods to add and mutliply rational numbers. Implement a method for return the value of a rational number as a double value. Write a driver class to test your class. here is the class details:

Constructor Summary: RationalNumber(int numerator, int denominator) Creates a new RationalNumber with given numerator and denominator. methods summary: RationalNumber add(RationalNumber rationaleNumber) Adds the given rationaleNumber to this RationalenNumber (the object that you created from RationalNumber Class) and returns the sum as a new RationalNumber. int getDenominator() Returns the denominator of this RationalNumber. double getDoubleValue() Returns the value of this RationalNumber as a double value. int getNumerator() Returns the numerator of this RationalNumber. RationalNumber multiply(RationalNumber rationalNumber) Multiplies the given rationalNumber to this RationalNumber (the object that you created from RationalNumber Class) and returns the product as a new RationalNumber

Ads

View Answers

April 25, 2011 at 4:05 PM

public class RationalClass { private int nr; private int dr; public int getDenominator() { return dr; } public int getNumerator() { return nr; } public RationalClass(int numerator, int denominator) { if (denominator == 0) { throw new RuntimeException("Denominator is zero"); } int no = rationalNumber(numerator, denominator); nr = numerator / no; dr = denominator / no; } public RationalClass add(RationalClass number) { int numerator = (this.nr * number.dr) + (this.dr * number.nr); int denominator = this.dr * number.dr; return new RationalClass(numerator, denominator); } public RationalClass multiply(RationalClass number) { return new RationalClass(this.nr * number.nr, this.dr * number.dr); } private static int rationalNumber(int p, int q) { if (q == 0) { return p; } else { return rationalNumber(q, p % q); } } public double getDoubleValue() { double num = Double.parseDouble(Integer.toString(getNumerator())); double den = Double.parseDouble(Integer.toString(getDenominator())); double value = num / den; return value; } public String toString() { return Double.toString(getDoubleValue()); } public static void main(String[] args) { RationalClass a, b, c; a = new RationalClass(1, 2); b = new RationalClass(1, 2); c = a.add(b); System.out.println("Addition= " + c); a = new RationalClass(1, 2); b = new RationalClass(1, 2); c = a.multiply(b); System.out.println("Multiplication= " + c); } }

April 25, 2011 at 4:05 PM

Ads

Related Tutorials/Questions & Answers: