Question

In: Computer Science

IN JAVA Rational Numbers Create a Rational number class in the same style as the Complex...

IN JAVA

Rational Numbers

Create a Rational number class in the same style as the Complex number class created in class. That is, implement the following methods:

  • constructor
  • add
  • sub
  • mul
  • div
  • toString

You must also provide a Main class and main method to fully test your Rational number class.

Solutions

Expert Solution

==================================================================

Program code to copy:

RationalNumber.java

/**
* RationalNumber.java
* Java class to represent one rational number with a numerator and denominator.
*/
public class RationalNumber {
  
   /* Class instance variables or data fields */
   private int numerator, denominator;
  
   /**
   * Constructor: Sets up the rational number by ensuring a nonzero denominator
   * and making only the numerator signed.
   * @param numer
   * @param denom
   */
   public RationalNumber(int numer, int denom) {
       if (denom == 0)
           denom = 1;

       // Make the numerator "store" the sign
       if (denom < 0) {
           numer = numer * -1;
           denom = denom * -1;
       }

       numerator = numer;
       denominator = denom;

       reduce();
   }
  
   /**
   * Accessor method for field numerator
   * @return numerator of this rational number.
   */
   public int getNumerator() {
       return numerator;
   }
  
   /**
   * Accessor method for field denominator
   * @return denominator of this rational number.
   */
   public int getDenominator() {
       return denominator;
   }
  
   /* Method to find reciprocal of this rational number. */
   public RationalNumber reciprocal() {
       return new RationalNumber(denominator, numerator);
   }
  
   /**
   * Method to add this rational number to the one passed as a parameter.
   * A common denominator is found by multiplying the individual denominators.
   * @param op2
   * @return addition of two rational numbers.
   */
   public RationalNumber add(RationalNumber op2) {
       int commonDenominator = denominator * op2.getDenominator();
       int numerator1 = numerator * op2.getDenominator();
       int numerator2 = op2.getNumerator() * denominator;
       int sum = numerator1 + numerator2;

       return new RationalNumber(sum, commonDenominator);
   }
  
   /**
   * Method to Subtract the rational number passed as a parameter
   * from this rational number.
   * @param op2
   * @return difference of two rational numbers.
   */
   public RationalNumber subtract(RationalNumber op2) {
       int commonDenominator = denominator * op2.getDenominator();
       int numerator1 = numerator * op2.getDenominator();
       int numerator2 = op2.getNumerator() * denominator;
       int difference = numerator1 - numerator2;

       return new RationalNumber(difference, commonDenominator);
   }
  
   /**
   * Method to Multiply this rational number by the one passed as a parameter.
   * @param op2
   * @return product of two rational numbers
   */
   public RationalNumber multiply(RationalNumber op2) {
       int numer = numerator * op2.getNumerator();
       int denom = denominator * op2.getDenominator();

       return new RationalNumber(numer, denom);
   }
  
   /**
   * Divides this rational number by the one passed as a parameter
   * by multiplying by the reciprocal of the second rational.
   * @param op2
   * @return division of two rational numbers.
   */
   public RationalNumber divide(RationalNumber op2) {
       return multiply(op2.reciprocal());
   }
  
   /**
   * Determines if this rational number is equal to the one passed
   * as a parameter. Assumes they are both reduced.
   * @param op2
   * @return true / false indicating equality of two rational numbers
   */
   public boolean equals(RationalNumber op2) {
       return (numerator == op2.getNumerator() && denominator == op2.getDenominator());
   }
  
   /**
   * @return rational number in string format
   */
   public String toString() {
       String result;

       if (numerator == 0)
           result = "0";
       else if (denominator == 1)
           result = numerator + "";
       else
           result = numerator + "/" + denominator;

       return result;
   }
  
   /**
   * Method to minimize the rational number
   * Reduces this rational number by dividing both the numerator
   * and the denominator by their greatest common divisor.
   */
   private void reduce() {
       if (numerator != 0) {
           int common = gcd(Math.abs(numerator), denominator);

           numerator = numerator / common;
           denominator = denominator / common;
       }
   }
  
   /**
   * Method to find the greatest common divisor of the two
   * positive parameters. Uses Euclid's algorithm.
   * @param num1
   * @param num2
   * @return greatest common divisor of the two positive parameters.
   */
   private int gcd(int num1, int num2) {
       while (num1 != num2)
           if (num1 > num2)
               num1 = num1 - num2;
           else
               num2 = num2 - num1;

       return num1;
   }
  
} /* End of class RationalNUmber */

TestRationalNumber.java

/* Java class to test RationalNumber class */
public class TestRationalNumber {

   /* Main or Driver method to test RationalNumber class methods */
   public static void main(String[] args) {
      
       /* Creating instances of RationalNumber class */
       RationalNumber rn1 = new RationalNumber(10, 4);
       RationalNumber rn2 = new RationalNumber(11, 6);
      
       /* Displaying rational numbers in string format */
       System.out.println("Rational Number1: " + rn1);
       System.out.println("Rational Number2: " + rn2);
      
       /* Displaying manipulations with rational numbers */
       System.out.println();
       System.out.println("Sum: "+ rn1.add(rn2));
       System.out.println("Difference: "+ rn1.subtract(rn2));
       System.out.println("Product: "+ rn1.multiply(rn2));
       System.out.println("Division: "+rn1.divide(rn2));
      
   } /* End of main method */

} /* End of TestRationalNumber class */

-------------------------------------------------------

Program code screenshot:

RationalNumber.java

TestRationalNumber.java

-----------------------------------------------------------

Sample Output:

==================================================================

Hope it will helpfull and do commets for any additional info if needed. Thankyou

==================================================================


Related Solutions

n Java, Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have...
n Java, Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have the form realPart + imaginaryPart * i where i is square root of -1 Use floating-point variables to represent the private data of the class. Provide a constructor that enables an object of this class to be initialized when it is declared. Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods that perform the following operations: a)...
Define a class called Rational for rational numbers. Arational number is a number that can...
Define a class called Rational for rational numbers. A rational number is a number that can be represented as the quotient of two integers. For example, /2, 3/4, 64/2, and so forth are all rational numbers.Represent rational numbers as two private values of type int, numfor the numerator and den for the denominator. The class has a default constructor with default values (num = 0,den = 1), a copy constructor, an assignment operator and three friend functions for operator overloading...
Must be coded in C#. 10.8 (Rational Numbers) Create a class called Rational for performing arithmetic...
Must be coded in C#. 10.8 (Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write an app 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...
Write a rational number class in C++. Recall a rational number is a rational number, composed...
Write a rational number class in C++. Recall a rational number is a rational number, composed of two integers with division indicated. The division is not carried out, it is only indicated, as in 1/2, 2/3, 15/32. You should represent rational numbers using two int values, numerator and denominator. A principle of abstract data type construction is that constructors must be present to create objects with any legal values. You should provide the following two constructors: one constructor to make...
The following program will be written in JAVA. Create a class called complex performing arithmetic with...
The following program will be written in JAVA. Create a class called complex performing arithmetic with complex numbers. Write a program to test your class.                         Complex numbers have the form:                         realPart + imaginaryPart * i                                               ___                         Where i is sqrt(-1)                                                 Use double variables to represent data of the class. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should contain default values in...
Task Create a class called Mixed. Objects of type Mixed will store and manage rational numbers...
Task Create a class called Mixed. Objects of type Mixed will store and manage rational numbers in a mixed number format (integer part and a fraction part). The class, along with the required operator overloads, should be written in the files mixed.h and mixed.cpp. Details and Requirements Finish Lab 2 by creating a Mixed class definition with constructor functions and some methods. The Mixed class should have public member functions Evaluate(), ToFraction(), and Simplify(). The Evaluate() function should return a...
ASAP (Math: The Complex class) A complex number is a number in the form a +...
ASAP (Math: The Complex class) A complex number is a number in the form a + bi, where a and b are real numbers and i is sqrt( -1). The numbers a and b are known as the real part and imaginary part of the complex number, respectively. You can perform addition, subtraction, multiplication, and division for complex numbers using the following formulas: a + bi + c + di = (a + c) + (b + d)i a +...
9.6 (Rational Class) Create a class called Rational (separate the files as shown in the chapter)...
9.6 (Rational Class) Create a class called Rational (separate the files as shown in the chapter) for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private data 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 contain default values in case no initializers are provided and should store the fraction in reduced form. For...
Create a class for working with complex numbers. Only 2 private float data members are needed,...
Create a class for working with complex numbers. Only 2 private float data members are needed, the real part of the complex number and the imaginary part of the complex number. The following methods should be in your class:a. A default constructor that uses default arguments in case no initializers are included in the main.b. Add two complex numbers and store the sum.c. Subtract two complex numbers and store the difference.d. Multiply two complex numbers and store the product.e. Print...
Java Beginner a)Create a class named Student that has fields for an ID number, number of...
Java Beginner a)Create a class named Student that has fields for an ID number, number of credit hours earned, and number of points earned. (For example, many schools compute grade point averages based on a scale of 4, so a three-credit-hour class in which a student earns an A is worth 12 points.) Include methods to assign values to all fields. A Student also has a field for grade point average. Include a method to compute the grade point average...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT