Question

Create a fraction class. This will have two attributes, a numerator and a denominator, both int....

Create a fraction class. This will have two attributes, a numerator and a denominator, both int. This class will have

  • constructors
  • accessors and mutators (for the attributes)
  • a toString method which will allow us to print the fraction in the form 3/4
  • an Add method so we can add two fractions
  • a subtract method (subtracts one fraction from the other)
  • a multiply method (multiply two fractions)
  • a divide method (divides one fraction by the other)

DO NOT (for now) worry about reducing the fractions.

//Code to copy into program

public class H4{

{

private int num; // Numerator   

private int den; // Denominator   

public Fraction()

{

// set fraction to default = 0/1

setFraction(0, 1);

} // end default constructor

public Fraction(int numerator, int denominator)

{

setFraction(numerator, denominator);

this.reduceToLowestTerms(); //called to reduce to lowest terms

} // end constructor

public int getNumerator()

{

return num;

} // end getNumerator

public int getDenominator()

{

return den;

} // end getDenominator

public Fraction add(Fraction secondFraction)

{

// a/b + c/d is (ad + cb)/(bd)

int resultDen;

int resultNum;

resultDen = this.getDenominator()*secondFraction.getDenominator();

resultNum = (this.getNumerator()*secondFraction.getDenominator())+(secondFraction.getNumerator()*this.getDenominator());

Fraction sum = new Fraction(resultNum, resultDen);

sum.reduceToLowestTerms();

return sum;

} // end add

public Fraction subtract(Fraction secondFraction)

{

// a/b - c/d is (ad - cb)/(bd)

int resultDen;

int resultNum;

resultDen = this.getDenominator()*secondFraction.getDenominator();

resultNum = (this.getNumerator()*secondFraction.getDenominator())-(secondFraction.getNumerator()*this.getDenominator());

Fraction difference = new Fraction(resultNum, resultDen);

difference.reduceToLowestTerms();

return difference;

} // end subtract

public Fraction multiply(Fraction secondFraction)

{

// a/b * c/d is (ac)/(bd)

int resultDen;

int resultNum;

resultNum = this.getNumerator()*secondFraction.getNumerator();

resultDen = this.getDenominator()*secondFraction.getDenominator();

Fraction product = new Fraction(resultNum, resultDen);

product.reduceToLowestTerms();

return product;

} // end multiply

public Fraction divide(Fraction secondFraction)

{

// return ArithmeticException if secondFraction is 0

if(secondFraction.getNumerator()==0)

throw new ArithmeticException("Second fraction is 0");

// a/b / c/d is (ad)/(bc)

int resultDen;

int resultNum;

resultNum = this.getNumerator()*secondFraction.getDenominator();

resultDen = this.getDenominator()*secondFraction.getNumerator();

Fraction divideResult = new Fraction(resultNum, resultDen);

divideResult.reduceToLowestTerms();

return divideResult;

} // end divide

public Fraction getReciprocal()

{

// return ArithmeticException if secondFraction is 0

if(this.getNumerator()==0)

throw new ArithmeticException("Reciprocal is not valid");

return new Fraction(this.den, this.num);

} // end getReciprocal

public boolean equals(Object other)

{

// implement this method!

Fraction secondFraction = (Fraction) other;

if(this.num==secondFraction.getNumerator() && this.den==secondFraction.getDenominator()){

return true;

}

else

return false;

} // end equals

public int compareTo(Fraction other)

{

// implement this method!

double fraction = (double)num/(double)den;

double otherFraction = (double)other.getNumerator()/(double)other.getDenominator();

if(otherFraction==fraction)

return 0;

else

return (int) (otherFraction-fraction);

} // end compareTo

public String toString()

{

if(den==1){

return String.valueOf(num);

}

else

return num + "/" + den;

} // end toString

/** Task: Reduces a fraction to lowest terms. */

//-----------------------------------------------------------------

// private methods start here

//-----------------------------------------------------------------

/**

* This method sets the numerator and denominator.

* @param numerator

* @param denominator

* @throws ArithmeticException if denominator is 0

*/

private void setFraction(int numerator, int denominator)

{

// return ArithmeticException if initialDenominator is 0

if(denominator==0)

throw new ArithmeticException("Denominator can't be 0");

// handle negative denominators to make it easy

if(denominator<0){

//swap the negative sign of denominator to numerator

this.den = Math.abs(denominator);

this.num = -numerator;

}

else{

this.num = numerator;

this.den = denominator;

}

} // end setFraction

private void reduceToLowestTerms()

{

// implement this method!

//

// Outline:

// compute GCD of num & den

int gcd = greatestCommonDivisor(num, den);

// greatestCommonDivisor works for + numbers.

// So, you should eliminate - sign

gcd = Math.abs(gcd);

// then reduce numbers : num/GCD and den/GCD

this.num = num/gcd;

this.den = den/gcd;

} // end reduceToLowestTerms

/** Task: Computes the greatest common secondFraction of two integers.

* @param integerOne an integer

* @param integerTwo another integer

* @return the greatest common divisor of the two integers */

private int greatestCommonDivisor(int integerOne, int integerTwo)

{

int result;

if (integerOne % integerTwo == 0)

result = integerTwo;

else

result = greatestCommonDivisor(integerTwo, integerOne % integerTwo);

return result;

} // end greatestCommonDivisor

public static void main(String[] args) {

Fraction fraction1 = new Fraction(2, 5);

Fraction fraction2 = new Fraction(16, 22); // will be reduced to lowest terms

// Just a check

System.out.println("Fraction 1 is: "+fraction1);

System.out.println("Fraction 3 is: "+fraction2);

System.out.println("Sum of the two fractions: "+fraction1.add(fraction2));

System.out.println("Difference (fraction1-fraction2): "+fraction1.subtract(fraction2));

System.out.println("Product of the two fractions: "+fraction1.multiply(fraction2));

System.out.println("fraction1/fraction2: "+fraction1.divide(fraction2));

}

} // end Fraction

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

//Change the name of class as Fraction

public class Fraction{

private int num; // Numerator

private int den; // Denominator

public Fraction()

{

// set fraction to default = 0/1

setFraction(0, 1);

} // end default constructor

public Fraction(int numerator, int denominator)

{

setFraction(numerator, denominator);

this.reduceToLowestTerms(); //called to reduce to lowest terms

} // end constructor

public int getNumerator()

{

return num;

} // end getNumerator

public int getDenominator()

{

return den;

} // end getDenominator

public Fraction add(Fraction secondFraction)

{

// a/b + c/d is (ad + cb)/(bd)

int resultDen;

int resultNum;

resultDen = this.getDenominator()*secondFraction.getDenominator();

resultNum = (this.getNumerator()*secondFraction.getDenominator())+(secondFraction.getNumerator()*this.getDenominator());

Fraction sum = new Fraction(resultNum, resultDen);

sum.reduceToLowestTerms();

return sum;

} // end add

public Fraction subtract(Fraction secondFraction)

{

// a/b - c/d is (ad - cb)/(bd)

int resultDen;

int resultNum;

resultDen = this.getDenominator()*secondFraction.getDenominator();

resultNum = (this.getNumerator()*secondFraction.getDenominator())-(secondFraction.getNumerator()*this.getDenominator());

Fraction difference = new Fraction(resultNum, resultDen);

difference.reduceToLowestTerms();

return difference;

} // end subtract

public Fraction multiply(Fraction secondFraction)

{

// a/b * c/d is (ac)/(bd)

int resultDen;

int resultNum;

resultNum = this.getNumerator()*secondFraction.getNumerator();

resultDen = this.getDenominator()*secondFraction.getDenominator();

Fraction product = new Fraction(resultNum, resultDen);

product.reduceToLowestTerms();

return product;

} // end multiply

public Fraction divide(Fraction secondFraction)

{

// return ArithmeticException if secondFraction is 0

if(secondFraction.getNumerator()==0)

throw new ArithmeticException("Second fraction is 0");

// a/b / c/d is (ad)/(bc)

int resultDen;

int resultNum;

resultNum = this.getNumerator()*secondFraction.getDenominator();

resultDen = this.getDenominator()*secondFraction.getNumerator();

Fraction divideResult = new Fraction(resultNum, resultDen);

divideResult.reduceToLowestTerms();

return divideResult;

} // end divide

public Fraction getReciprocal()

{

// return ArithmeticException if secondFraction is 0

if(this.getNumerator()==0)

throw new ArithmeticException("Reciprocal is not valid");

return new Fraction(this.den, this.num);

} // end getReciprocal

public boolean equals(Object other)

{

// implement this method!

Fraction secondFraction = (Fraction) other;

if(this.num==secondFraction.getNumerator() && this.den==secondFraction.getDenominator()){

return true;

}

else

return false;

} // end equals

public int compareTo(Fraction other)

{

// implement this method!

double fraction = (double)num/(double)den;

double otherFraction = (double)other.getNumerator()/(double)other.getDenominator();

if(otherFraction==fraction)

return 0;

else

return (int) (otherFraction-fraction);

} // end compareTo

public String toString()

{

if(den==1){

return String.valueOf(num);

}

else

return num + "/" + den;

} // end toString

/** Task: Reduces a fraction to lowest terms. */

//-----------------------------------------------------------------

// private methods start here

//-----------------------------------------------------------------

/**

* This method sets the numerator and denominator.

* @param numerator

* @param denominator

* @throws ArithmeticException if denominator is 0

*/

private void setFraction(int numerator, int denominator)

{

// return ArithmeticException if initialDenominator is 0

if(denominator==0)

throw new ArithmeticException("Denominator can't be 0");

// handle negative denominators to make it easy

if(denominator<0){

//swap the negative sign of denominator to numerator

this.den = Math.abs(denominator);

this.num = -numerator;

}

else{

this.num = numerator;

this.den = denominator;

}

} // end setFraction

private void reduceToLowestTerms()

{

// implement this method!

//

// Outline:

// compute GCD of num & den

int gcd = greatestCommonDivisor(num, den);

// greatestCommonDivisor works for + numbers.

// So, you should eliminate - sign

gcd = Math.abs(gcd);

// then reduce numbers : num/GCD and den/GCD

this.num = num/gcd;

this.den = den/gcd;

} // end reduceToLowestTerms

/** Task: Computes the greatest common secondFraction of two integers.

* @param integerOne an integer

* @param integerTwo another integer

* @return the greatest common divisor of the two integers */

private int greatestCommonDivisor(int integerOne, int integerTwo)

{

int result;

if (integerOne % integerTwo == 0)

result = integerTwo;

else

result = greatestCommonDivisor(integerTwo, integerOne % integerTwo);

return result;

} // end greatestCommonDivisor

public static void main(String[] args) {

Fraction fraction1 = new Fraction(2, 5);

Fraction fraction2 = new Fraction(16, 22); // will be reduced to lowest terms

// Just a check

System.out.println("Fraction 1 is: "+fraction1);

System.out.println("Fraction 3 is: "+fraction2);

System.out.println("Sum of the two fractions: "+fraction1.add(fraction2));

System.out.println("Difference (fraction1-fraction2): "+fraction1.subtract(fraction2));

System.out.println("Product of the two fractions: "+fraction1.multiply(fraction2));

System.out.println("fraction1/fraction2: "+fraction1.divide(fraction2));

}

} // end Fraction

===========================
SEE OUTPUT

PLEASE COMMENT if there is any concern.

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

Add a comment
Know the answer?
Add Answer to:
Create a fraction class. This will have two attributes, a numerator and a denominator, both int....
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
  • 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...

  • public class Rational { // PUT PRIVATE DATA FIELDS HERE /** * The default constructor for...

    public class Rational { // PUT PRIVATE DATA FIELDS HERE /** * The default constructor for objects of class Rational. Creates the rational number 1. */ public Rational() { // ADD CODE TO THE CONSTRUCTOR } /** * The alternate constructor for objects of class Rational. Creates a rational number equivalent to n/d. * @param n The numerator of the rational number. * @param d The denominator of the rational number. */ public Rational(int n, int d) { // ADD...

  • Consider a class Fraction of fractions. Each fraction is signed and has a numerator and a...

    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 fractions are equal, and convert a fraction to...

  • I have provided a main method. Please add your fraction class. You need constructors, add, subtract,...

    I have provided a main method. Please add your fraction class. You need constructors, add, subtract, multiply, and divide methods, and a toString method. Your toString method needs to return the numerator followed by / followed by the denominator - NO spaces. DO NOT make any attempt to reduce the fractions (we shall do that later). Please add comments throughout. import java.util.Scanner; public class H4 { public static class Fraction { } public static void main(String[] args) { Fraction f=...

  • 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...

  • 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....

  • 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...

  • For the add method in Fraction class, fill the following blank. public Fraction add(Fraction f) {...

    For the add method in Fraction class, fill the following blank. public Fraction add(Fraction f) { int num = numerator * f.getDenominator() + f.getNumerator() * denominator; int denom = denominator * f.getDenominator(); return ww new Fraction(num, denom) num/denom (double)num/(double)denom (int)num/denom

  • This in in C# There are two classes, class Fraction and class FractionDemo The user needs...

    This in in C# There are two classes, class Fraction and class FractionDemo The user needs to be able to input a value for the numerator and the denominator Create a Fraction class with private fields that hold a positive int numerator and a positive int denominator. In addition, create Properties for each field with the set mutator such that the numerator is greater than or equal to 0 and the denominator is greater than 0 (illegal values should be...

  • 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)...

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