Question

Need help with following assignment written in Java. For this assignment, you’re going to create...

Need help with following assignment written in Java.

For this assignment, you’re going to create a new class named “Fraction” for managing rational numbers (fractions). (You should not submit a main program with the Fraction class; however, you'll definitely want to write one for your own testing purposes.) Details are as follows:

CLASS DEFINITION CONSTRUCTORS:

Fraction(int num,int denom)

num/denom

creates a new number whose value is

Fraction(int num)

METHODS (assume x is a Fraction):

creates a new number whose value is num/1

Fraction x.add(Fraction n)

Returns x+n in reduced form

Fraction x.sub(Fraction n)

Returns x-n in reduced form

Fraction x.mul(Fraction n)

Returns x*n in reduced form

Fraction x.div(Fraction n)

Returns x/n in reduced form

double x.toDouble()

Returns x as a double-precision floating point number

int getNum(),int getDenom()

Returns numerator or denominator

String toString()

Return a string representing the fraction,

as described below You may also want to make a private method:

                   private x.reduce()     Adjusts num and denom so num/denom

is in simplest form (as described below)

DETAILS

Make sure your program can utilize the following operations on rational numbers: addition, multiplication, etc. For reducing a fraction to simplest form, we’ll use Euclid’s Algorithm.

DIVISION BY 0

Fractions with denominators of 0 are arithmetically undefined, so if such a number is created, you should somehow note internally that the number is undefined. Note that any operations involving a undefined number result in an undefined number.

If toDouble() is used on an undefined number, return Double.NaN

ToString

You should create a method String toString() for treating Fractions as a String. A number of the form D/1 should convert as simply D (no “/1”). Care should be used with rationals with a negative num or a negative denom. For example, if num=1 and denom=-2 you should return -1/2 (not 1/-2); If num=-1 and denom=-2, you should return 1/2 (not -1/-2). An undefined number should return"NaN"

REDUCING NUMBERS

“Simplest form” means (a) eliminating any common integer factors from both num and denom; (b) adjusting num and denom so denom is not negative; and (c) changing 0/x to the form 0/1 (unless x=0, in which case this results in NaN).

0 0
Add a comment Improve this question Transcribed image text
Answer #1

We first write a class named, Fraction.java which follows just the definition given in the problem statement.

Note that you need to know the Euclid's Algorithm for implementing reduction of fractions:

Euclid's Algorithm(For finding greatest common divisor(highest common factor) of two positive integers, a and b:

ged(a, b) -\gcd if a -0 a) gcd(b mod a) otherwise

Here is the class declaration and definition, fully documented for better understanding:

***********************************************************************************************************************************************

Fraction.java:

public class Fraction{
   int numerator;   //integer for storing numerator of fraction
   int denominator;   //integer for storing denominator of fraction
   boolean valid;   //will be set to true if denominator is not zero else false
  
   //member functions now
  
   //Constructor 1
   public Fraction(int num, int denom){
       /*
       * This will initialize the class's numerator and denominator to num and denom resp.
       * We will make sure that we maintain simplest forms at all times
       * That is, we will not let denom to be negative and when denom is 0, we will set valid flag.
       * Also, if num is zero, we will make denominator to be 1.
       */
      
       //initially we set valid flag to be true
       valid = true;
       if(denom == 0){
           //this is the case where fraction is invalid
           numerator = num;
           denominator = denom;
           valid = false;   //we set the valid flag to be false
       }
       else if(num > 0 && denom > 0){
           numerator = num;
           denominator = denom;
       }
       else if(num > 0 && denom < 0){
           numerator = -1 * num;
           denominator = -1 * denom;
       }
       else if(num < 0 && denom > 0){
           numerator = num;
           denominator = denom;
       }
       else if(num < 0 && denom < 0){
           numerator = -1 * num;
           denominator = -1 * denom;
       }
       else if(num == 0){
           //here we set denominator to be 1.
           numerator = num;
           denominator = 1;
       }
   }
  
   //Constructor 2
   public Fraction(int num){
       /*
       * We simply create the fraction, num/1 and set its validity to be true
       */
       valid = true;
       numerator = num;
       denominator = 1;
   }
  
   //public functions for getting numerator, denominator and checking validity
   public int getNum(){
       return numerator;
   }
  
   public int getDenom(){
       return denominator;
   }
  
   public boolean checkValid(){
       return valid;
   }
  
   //private function for finding gcd of two positive numbers
   private int gcd(int num, int denom){
       /*
       * This function will use Euclid's algo. to find gcd of num and denom
       */
       if(num == 0)
           return denom;
       return gcd(denom%num, num);
   }
  
   //private function for reducing fraction to lowest form
   private void reduce(){
       /*
       * This function will apply Euclid's algorithm to find GCD of numerator and denominator, call it h.
       * Then we simply change numerator to numerator/h and denominator to denominator/h.
       * Of course, we must take care to not let denominator to be < 0 and when numerator is 0, we must change denominator to 1.
       * Also, we must not reduce an invalid fraction
       */
       if(!valid)   //check for validity of fraction to be reduced
           return;
       else if(numerator == 0){
           denominator = 1;
       }
       else if(numerator > 0 && denominator > 0){
           int h = gcd(numerator, denominator);
           numerator = numerator/h;
           denominator = denominator/h;
       }
       else if(numerator > 0 && denominator < 0){
           int h = gcd(numerator, -1 * denominator);
           numerator = -1 * (numerator/h);   //to make sure that numerator becomes negative and denominator is positive
           denominator = (-1 * denominator)/h;
       }
       else if(numerator < 0 && denominator > 0){
           int h = gcd(-1 * numerator, denominator);
           numerator = -1 * ((-1 * numerator)/h);   //to make sure that numerator becomes negative and denominator is positive
           denominator = denominator/h;
       }
       else if(numerator < 0 && denominator < 0){
           int h = gcd(-1 * numerator, -1 * denominator);
           numerator = (-1 * numerator)/h;   //to make sure that numerator becomes negative and denominator is positive
           denominator = (-1 * denominator)/h;
       }
   }
      
   public Fraction add(Fraction n){
       /*
       * This function will return x + n, where x = numerator/denominator
       * Care must be taken for handling NaN numbers, i.e. when either of x or n is invalid, we return invalid.
       * At last we must reduce the result.
       */
       if(!valid || !n.checkValid()){
           Fraction f = new Fraction(0, 0);
           return f;
       }
       else{
           /*
           * this means that both fractions are valid
           * for adding a/b + c/d; we take lcm of b and d. call it lcm(b, d)
           * answer is then: R = ((lcm(b, d)/b)*a + (lcm(b, d)/d)*c)/lcm(b, d)
           * then we reduce R to lowest form.
           * for finding lcm(b, d) = b*d/gcd(b, d)
          
           * First, we reduce x and n to lowest forms to ensure their denominators are positve and to reduce computations
           */
          
           reduce();   //reducing x
           n.reduce();   //reducing n
  
           //now we know for sure that both x's and n's denominators are positive
           int new_num;
           int new_denom;
           int hcf = gcd(denominator, n.getDenom());
           int lcm = (denominator * n.getDenom())/hcf;
          
           new_num = ((lcm/denominator) * numerator) + ((lcm/n.getDenom()) * n.getNum());
           new_denom = lcm;
           //we now create a fraction with numerator and denominator as new_num and new_denom resp.
           //we also must reduce the resulting fraction
           Fraction R = new Fraction(new_num, new_denom);
           R.reduce();
           return R;
       }
   }
      
   public Fraction sub(Fraction n){
       /*
       * This function will return x - n, where x = numerator/denominator
       * Care must be taken for handling NaN numbers, i.e. when either of x or n is invalid, we return invalid.
       * At last we must reduce the result.
       * This is exactly similar to add method(see above)
       */
       if(!valid || !n.checkValid()){
           Fraction f = new Fraction(0, 0);
           return f;
       }
       else{
           /*
           * this means that both fractions are valid
           * for subtracting a/b - c/d; we take lcm of b and d. call it lcm(b, d)
           * answer is then: R = ((lcm(b, d)/b)*a - (lcm(b, d)/d)*c)/lcm(b, d)
           * then we reduce R to lowest form.
           * for finding lcm(b, d) = b*d/gcd(b, d)
          
           * First, we reduce x and n to lowest forms to ensure their denominators are positve and to reduce computations
           */
          
           reduce();   //reducing x
           n.reduce();   //reducing n
  
           //now we know for sure that both x's and n's denominators are positive
           int new_num;
           int new_denom;
           int hcf = gcd(denominator, n.getDenom());
           int lcm = (denominator * n.getDenom())/hcf;
          
           new_num = ((lcm/denominator) * numerator) - ((lcm/n.getDenom()) * n.getNum());
           new_denom = lcm;
           //we now create a fraction with numerator and denominator as new_num and new_denom resp.
           //we also must reduce the resulting fraction
           Fraction R = new Fraction(new_num, new_denom);
           R.reduce();
           return R;
       }
   }
  
   public Fraction mul(Fraction n){
       /*
       * This function will return x * n, where x = numerator/denominator
       * Care must be taken for handling NaN numbers, i.e. when either of x or n is invalid, we return invalid.
       * At last we must reduce the result.
       */
       if(!valid || !n.checkValid()){
           Fraction f = new Fraction(0, 0);
           return f;
       }
       else{
           /*
           * this means that both fractions are valid
           * for multiplying a/b * c/d; we first reduce a/b and c/d to lowest forms
           * then we simply make the fraction as: (a'*c')/(b'*d'), where ' denotes reduced form of the corresponding variable
           */
          
           reduce();   //reducing x
           n.reduce();   //reducing n
  
           //now we know for sure that both x's and n's denominators are positive
           int new_num;
           int new_denom;
           new_num = (numerator * n.getNum());
           new_denom = (denominator * n.getDenom());
           //we now create a fraction with numerator and denominator as new_num and new_denom resp.
           //we also must reduce the resulting fraction
           Fraction R = new Fraction(new_num, new_denom);
           R.reduce();
           return R;
       }
   }
  
   public Fraction div(Fraction n){
       /*
       * This function will return x / n, where x = numerator/denominator
       * Care must be taken for handling NaN numbers, i.e. when either of x or n is invalid, we return invalid.
       * At last we must reduce the result.
       */
       if(!valid || !n.checkValid()){
           Fraction f = new Fraction(0, 0);
           return f;
       }
       else{
           /*
           * this means that both fractions are valid
           * for dividing (a/b) / (c/d); we first reduce a/b and c/d to lowest forms
           * division is equivalent to multiplying with the reciprocal.
           * then we simply make the fraction as: (a'*d')/(b'*c'), where ' denotes reduced form of the corresponding variable
           * however care must be taken to ensure that we are not dividing by zero, i.e. c must not be 0.
           */
          
           //now we check if n is 0 or not.
           if(n.getNum() == 0){
               Fraction f = new Fraction(0, 0);
               return f;
           }
          
           reduce();   //reducing x
           n.reduce();   //reducing n
           //now we know for sure that both x's and n's denominators are positive
           int new_num;
           int new_denom;
           new_num = (numerator * n.getDenom());
           new_denom = (denominator * n.getNum());
           //we now create a fraction with numerator and denominator as new_num and new_denom resp.
           //we also must reduce the resulting fraction
           Fraction R = new Fraction(new_num, new_denom);
           R.reduce();
           return R;
       }
   }
  
   public double toDouble(){
       /*
       * This function will return the floating point value of numerator/denominator
       * We must also check for validity of the fraction first
       */
       if(!valid)
           return Double.NaN;
      
       else{
           //we first reduce to make denominator positive and then simply divide numerator by denominator
           reduce();
           double ans = numerator * 1.0 / denominator;
           return ans;
       }
   }
  
   public String toString(){
       /*
       * This function will return the string representing the fraction
       */
       if(!valid)
           return "NaN";
       else if(numerator == 0)
           return "0/1";
       else if(denominator == 1)
           return Integer.toString(numerator);
       else if(numerator > 0 && denominator > 0)
           return Integer.toString(numerator) + "/" + Integer.toString(denominator);
       else if(numerator > 0 && denominator < 0)
           return Integer.toString(-1 * numerator) + "/" + Integer.toString(-1 * denominator);
       else if(numerator < 0 & denominator > 0)
           return Integer.toString(numerator) + "/" + Integer.toString(denominator);
       else
           //both are negative
           return Integer.toString(-1 * numerator) + "/" + Integer.toString(-1 * denominator);  
   }
}
                  
********************************************************************************************************************************************** Test class for testing the above class:

Test.java:

public class Test{
   public static void main(String[] args){
       Fraction f1 = new Fraction(-4); //change this to test according to your cases
       Fraction f2 = new Fraction(0, 5); //change this to test according to your cases
       Fraction f3 = f1.div(f2); //feel free to change the operation you want to test
       Fraction f4 = f1.add(f2); //feel free to change the operation you want to test
      
       System.out.println(f3.toString());
       System.out.println(f4.toDouble());
   }
}

**********************************************************************************************************************************************

Commands for compiling and running(On Linux/Ubuntu Machines):

> javac Fraction.java

> javac Test.java

> java Test

**********************************************************************************************************************************************
Sample Inputs and Outputs:

  • Note in all inputs/outputs, two lines of output will be shown, first corresponding to toString() method of the resulting fraction and second corresponding to toDouble() representation of the resulting fraction.

Addition:

Input:

f1 = new Fraction(4, 8);

f2 = new Fraction(3, 4);

f3 = f1.add(f2);

Output:

5/4
1.25   
-----------------------------------------------------------------------------   

Subtraction:

Input:

f1 = new Fraction(4, 8);

f2 = new Fraction(3, 4);

f3 = f1.sub(f2);

Output:

-1/4
-0.25

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

Multiplication:

Input:

f1 = new Fraction(-4);

f2 = new Fraction(3, 4);

f3 = f1.mul(f2);

Output:

-3
-3.0

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

Division:

Input:

f1 = new Fraction(-4);

f2 = new Fraction(3, 4);

f3 = f1.div(f2);

Output:

-16/3
-5.333333333333333

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

Reduction:

Input:

f1 = new Fraction(200, -15);

f2 = new Fraction(0. 1);

f3 = f1.add(f2);

Output:

-40/3
-13.333333333333334

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

Division by 0:

Input:

f1 = new Fraction(200, -15);

f2 = new Fraction(0. 1);

f3 = f1.div(f2);

Output:

NaN
NaN

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

***********************************************************************************************************************************************

Feel free to ask any doubts which you may have regarding the code! Cheers!
  
  
  
  
  
  
  
  
  
  

Add a comment
Know the answer?
Add Answer to:
Need help with following assignment written in Java. For this assignment, you’re going to create...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Adapt your Rational class : public class Rational { private int num; private int denom; public...

    Adapt your Rational class : public class Rational { private int num; private int denom; public Rational() { num = 0; denom = 1; } public Rational(int num, int denom) { this.num = num; this.denom = denom; } int getNum() { return num; } int getDenom() { return denom; } public Rational add(Rational rhs) { return new Rational(num * rhs.denom + rhs.num * denom, denom * rhs.denom); } public Rational subtract(Rational rhs) { return new Rational(num * rhs.denom - rhs.num...

  • Having to repost this as the last answer wasn't functional. Please help In the following program...

    Having to repost this as the last answer wasn't functional. Please help In the following program written in C++, I am having an issue that I cannot get the reducdedForm function in the Rational.cpp file to work. I cant figure out how to get this to work correctly, so the program will take what a user enters for fractions, and does the appropriate arithmetic to the two fractions and simplifies the answer. Rational.h class Rational { private: int num; int...

  • When we test your Fraction.java we will use the given FractionTester.java file. Your Fraction.java file -MUST-...

    When we test your Fraction.java we will use the given FractionTester.java file. Your Fraction.java file -MUST- work perfectly with the supplied FractionTester.java file. You may NOT modify the FractionTester to make your Fraction class work right. Starter Fraction File: Fraction.java ADD METHODS TO THIS FILE. HAND IN THIS FILE ONLY. Given/Completed Tester File: FractionTester.java DO NOT MODIFY. DO NOT HAND IN. You are to add the following methods to the given Fraction.java file public Fraction add( Fraction other) returns a...

  • Please use Java language. Thanks in advance. HOME WORK due 09. 18.2019 (Rational Numbers) Create a...

    Please use Java language. Thanks in advance. HOME WORK due 09. 18.2019 (Rational Numbers) 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. The constructor should store the fraction in reduced form. The fraction 2/4 is equivalent to 2...

  • I need help with the following Java code Consider a class Fraction of fractions. Each fraction...

    I need help with the following Java code Consider a class Fraction of fractions. Each fraction is signed and has a numerator and a denominator that are integers. Your class should be able to add, subtract, multiply, and divide two fractions. These methods should have a fraction as a parameter and should return the result of the operation as a fraction. The class should also be able to find the reciprocal of a fraction, compare two fractions, decide whether two...

  • Lab 1.java only Goal: This lab will give you experience with defining and using classes and...

    Lab 1.java only Goal: This lab will give you experience with defining and using classes and fields, and with conditionals and recursive functions. Getting Started --------------- Read the Fraction.java class into a text editor and compile it filling in the command javac -g Fraction.java. The program should compile without errors. In a shell window, run the program using "java Fraction". The program should run, although it will print fractions in a non-reduced form, like 12/20. Part I: Constructors (1 point)...

  • Rational will be our parent class that I included to this post, Implement a sub-class MixedRational....

    Rational will be our parent class that I included to this post, Implement a sub-class MixedRational. This class should Implement not limited to: 1) a Constructor with a mathematically proper whole, numerator and denominator values as parameters. 2) You will override the: toString, add, subtract, multiply, and divide methods. You may need to implement some additional methods, enabling utilization of methods from rational. I have included a MixedRational class with the method headers that I used to meet these expectations....

  • Rational Number *In Java* A rational number is one that can be expressed as the ratio...

    Rational Number *In Java* A rational number is one that can be expressed as the ratio of two integers, i.e., a number that can be expressed using a fraction whose numerator and denominator are integers. Examples of rational numbers are 1/2, 3/4 and 2/1. Rational numbers are thus no more than the fractions you've been familiar with since grade school. Rational numbers can be negated, inverted, added, subtracted, multiplied, and divided in the usual manner: The inverse, or reciprocal of...

  • (Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write a program to...

    (Rational Numbers) 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. The constructor should store the fraction in reduced form. The fraction 2/4 is equivalent to h and would be stored in the object as 1 in the numerator...

  • Need help with Java for Fraction exercise

    Add another public method called add to your Fraction class. This method adds another fraction to the ‘calling object’. Thus, the method will take a Fraction class object as a parameter, add this parameter fraction to the calling object (fraction), and return a Fraction object as a result. HINT: We can use cross multiplication to determine the numerator of the resultant Fraction. The denominator of the resultant Fraction is simply the multiplication of the denominators of the two other Fractions.Add...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT