Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write and fully test a class that represents rational numbers. A rational number

ID: 3651640 • Letter: W

Question

Write and fully test a class that represents rational numbers. A rational number can be represented as the ratio of two integer values, a and b, where b is not zero. The class has attributes fir the numerator and denominator of this ratio. The ratio should always be stored in its simplest form. That is, any common factor of a and b should be removed. For example the rational number 40/12 should be stored as 10/3.


The class has the following constructors and methods.


1) A default constructor that sets the rational number to 0/1

2) A constructor that has parameters for the numerator and denominator and converts the resulting ratio to simplified form.

3) simplify - a private method that converts the rational number to simplified form.

4) getGCD(x, y) - a private static method that returns the largest common factor of the two positive integers x and y, that is, their greatest common divisor. For example, the greatest common divisor of 40 and 12 is 4.

5) getValue - returns the rational number as a double value

6) toString - returns the rational number as a string in the form a/b

Explanation / Answer

public class Rational { private int numerator; private int denominator; public Rational(){ numerator = 0;//it defaults to this anyway denominator = 0;//this really shouldn't be 0 } //step g. public Rational(int numerator, int denominator){ this.numerator = numerator; this.denominator = denominator; } public static void printRational(Rational number){ } public void negate(){ } public void invert(){ } public double toDouble(){ double value = 0.0; return value; } /** * Determines greatest common denominator and if greater than 1, * applies it to create a new Rational object with * reduced numerator and denominator. * * @return new reduced Rational object. If gcd is 1, * returns reference to this Rational object. */ public Rational reduce(){ Rational reduced = null; int gcd = gcd(); //check to see if 1 //if 1, return this //else, apply to instance vars to //get new values to use //to create a new Rational return reduced; } private int gcd(){ int gcd = 1; return gcd; } public static Rational add(Rational first, Rational second){ Rational result = null; return result; } public static void main(String[] args) { Rational defaultRational = new Rational(); Rational.printRational( defaultRational); Rational positive = new Rational(2, 3); positive.negate(); Rational.printRational(positive); Rational fiveThirds = new Rational(5, 3); fiveThirds.invert(); Rational.printRational(fiveThirds); System.out.println( fiveThirds.toDouble() ); //more tests... } }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote