Question

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

Your class should handle denominators that are zero. Fractions should always occur in lowest terms, and the class should be responsible for this requirement. For example, if the user tries to create a fraction such as 4/8, the class should set the fraction to 1/2. Likewise, the results of all arithmetic operations should be in lowest terms. Note that a fraction can be improper - that is, have a numerator that is larger than its denominator. Such a fraction, however, should be in lowest terms.

At this stage, design, but do not implement, the class Fraction. Begin by listing all the needed operations. Then write a Java interface, named FractionInterface, that declares each public method. This interface needs to declare following methods: setFraction, getNumerator, getDenominator, add, subtract, multiply, divide, and getReciprocal. Include javadoc-style comments to specify each method.

Now, write a Java class Fraction that implements the FractionInterface you designed. Begin with reasonable constructors. Design and implement useful private methods, if needed, and include comments that specify them.

To reduce a fraction such as 4/8 to lowest terms, you need to divide both the numerator and the denominator by their greatest common divisor. The greatest common divisor of 4 and 8 is 4, so when you divide the numerator and denominator of 4/8 by 4, you get the fraction 1/2. The following recursive algorithm finds the greatest common denominator of two positive integers:

Algorithm gcd(integerOne, integerTwo) 

if(integerOne % integerTwo == 0)

 result = integerTwo

else

 result = gcd(integerTwo, integerOne % integerTwo)

return result

It will be easier to determine the correct sign of a fraction if you force the fraction's denominator to be positive. However, your implementation must handle negative denominators that the client might provide. Write a program that adequately demonstrates your class.

Finally, your Fraction class needs to extend java.lang.Number class and implement java.lang.Comparable interface (in addition to FractionInterface . It will also need to override the toString and equals methods of Object class.

This is what I have so far, i need help with the areas marked to do. As well as my lowestTerms method, this method is not working at all. One problem I am having is that some methods have to return a fraction but the answer should return as 0. For example, in the get reciprocal method, if the numerator is 0 the result of the method should be 0, but 0 is not a fraction so.

/**

* Fraction class that performs basic math operations such

* as add, subtract, multiply, and divide. The class can

* also get the reciprocal of a fraction, compare two fractions,

* determine if two fractions are equal, and obtain the string form

* of a fraction. The class can handle denominators of 0, negative

* numbers and improper fractions.

*

*/

public class Fraction extends java.lang.Number implements FractionInterface, java.lang.Comparable<Fraction>

{

/**

* Data field for the numerator

*/

private int numerator;

/**

* Data field for the denominator

*/

private int denominator;

  

/**

* No arg constructor that sets the numerator

* and denominator to 0.

*/

  

public Fraction()

{

this.numerator = 0;

this.denominator = 0;

}

  

/**

* Constructor that initializes the given numbers to the

* numerator and denominator for the fraction

* @param numerator

* @param denominator

*/

  

public Fraction(int givenNumerator, int givenDenominator)

{

setFraction(givenNumerator, givenDenominator);

}

  

/**

* Constructor that takes a fraction object as a parameter

* @param newFraction

*/

  

public Fraction (Fraction newFraction)

{

this.numerator = newFraction.numerator;

this.denominator = newFraction.denominator;

setFraction(numerator,denominator);

}

  

/**

* Sets a fraction

* @param numerator

* @param denominator

*/

  

public void setFraction(int numerator, int denominator)

{

this.numerator = numerator;

if (denominator == 0)

{

throw new IllegalFractionException("Denominator can not be zero");

}

else

{

this.denominator = denominator;

}

this.adjustSign();

this.lowestTerms();

}

  

/**

* Determines the greatest common divisor between two integers

* @param a

* @param b

* @return an integer that is the gcd

*/

  

private int gcd(int a, int b)

{

int result;

if (a % b == 0)

{

result = b;

}

else

{

result = gcd(b, a % b);

}

return result;

}

  

  

/**

* Puts the fraction into its lowest terms using the gcd method

* @return the lowest terms of a fraction

*/

  

private Fraction lowestTerms()

{

Fraction newFraction = new Fraction(numerator, denominator);

if (numerator == 0)

{

newFraction = new Fraction(numerator, denominator);

return newFraction;

}

else

{

int GCD = gcd(Math.abs(numerator), Math.abs(denominator));

numerator = this.getNumerator() / GCD;

denominator = this.getDenominator() / GCD;

newFraction = new Fraction(numerator, denominator);

}

return newFraction;

}

  

  

/**

* Obtains the numerator

* @return numerator

*/

  

public int getNumerator()

{

return numerator;

}

  

/**

* Obtains the denominator

* @return denominator

*/

  

public int getDenominator()

{

return denominator;

}

  

  

/**

* Sets the numerator to the given value

* @param newNumerator

* @return the value of the numerator

*/

  

public int setNumerator(int newNumerator)

{

this.numerator = newNumerator;

lowestTerms();

return numerator;

}

  

public int setDenominator(int newDenominator)

{

if (denominator == 0)

{

throw new IllegalFractionException("Denominator can not be zero");

}

else

{

this.denominator = newDenominator;

}

adjustSign();

lowestTerms();

return denominator;

}

  

  

/**

* Obtains the fraction's sign.

* @return the fraction's sign

*/

  

public char getSign()

{

char sign;

this.adjustSign();

if (numerator >= 0)

{

sign = '+';

}

else

{

sign = '-';

}

return sign;

}

  

  

/**

* Sets the numerator's sign to the fraction's sign

* and sets the denominator's sign to positive

*/

  

public void adjustSign()

{

if (denominator < 0)

{

numerator = numerator * -1;

denominator = denominator * -1;

}

else

{

return;

}

}

  

  

/**

* Adds two fractions together

* @param

*/

  

public FractionInterface add(FractionInterface otherFraction)

{

Fraction othFra = (Fraction) otherFraction;

Fraction sum;

this.adjustSign();

othFra.adjustSign();

this.lowestTerms();

othFra.lowestTerms();

if ((this.numerator == 0) && (othFra.numerator == 0))

{

sum = new Fraction(); //TODO should return 0

}

else

{

int newNumerator = this.numerator * othFra.denominator + othFra.numerator * this.denominator;

int newDenominator = this.denominator * othFra.denominator;

sum = new Fraction(newNumerator, newDenominator);

}

return sum;

}

  

  

/**

* Subtracts two fractions

* @param

*/

  

public FractionInterface subtract(FractionInterface otherFraction)

{

Fraction othFra = (Fraction) otherFraction;

Fraction difference;

this.adjustSign();

othFra.adjustSign();

this.lowestTerms();

othFra.lowestTerms();

if ((this.numerator == 0) && (othFra.numerator == 0))

{

difference = new Fraction(); //TODO

}

else

{

int newNumerator = this.numerator * othFra.denominator - othFra.numerator * this.denominator;

int newDenominator = this.denominator * othFra.denominator;

difference = new Fraction(newNumerator, newDenominator);

}

return difference;

}

  

/**

* Multiples two fractions together

* @param

*/

public FractionInterface multiply(FractionInterface otherFraction)

{

Fraction othFra = (Fraction) otherFraction;

Fraction product;

this.adjustSign();

othFra.adjustSign();

this.lowestTerms();

othFra.lowestTerms();

if ((this.numerator == 0) && (othFra.numerator == 0))

{

product = new Fraction(); //TODO

}

else

{

int newNumerator = this.numerator * othFra.numerator;

int newDenominator = this.denominator * othFra.denominator;

if (newNumerator == 0)

{

product = new Fraction(); //TODO

}

else

{

product = new Fraction(newNumerator, newDenominator);

}

}

return product;

}

  

/**

* Divides two fractions

* @param

*/

  

public FractionInterface divide(FractionInterface otherFraction)

{

Fraction othFra = (Fraction) otherFraction;

Fraction quotient;

this.adjustSign();

othFra.adjustSign();

this.lowestTerms();

othFra.lowestTerms();

if (othFra.numerator == 0)

{

throw new IllegalFractionException("Divisor is 0");

}

else if (this.numerator == 0)

{

quotient = new Fraction(); //TODO

}

else

{

int newNumerator = numerator * othFra.denominator;

int newDenominator = denominator * othFra.numerator;

quotient = new Fraction(newNumerator, newDenominator);

}

return quotient;

}

  

/**

* Obtains the reciprocal of a fraction

* @return

*/

  

public Fraction getReciprocal()

{

Fraction reciprocal;

if(numerator == 0)

{

reciprocal = new Fraction(); //TODO this should return 0, but since

//it has to return a fraction i dnt know what to do

}

else

{

reciprocal = new Fraction(denominator, numerator);

}

return reciprocal;

}

  

  

/**

* Compares two fractions together and returns 0 if the

* fractions are the same, return negative or positive if

* the fraction is smaller or larger than the other fraction

* @param obj

* @return integer that represents result

*/

  

@Override

  

public int compareTo(Fraction obj)

{

int result = 100;

this.adjustSign();

this.lowestTerms();

obj.adjustSign();

this.lowestTerms();

obj.lowestTerms();

if ((numerator == obj.numerator) && (denominator == obj.denominator))

{

result = 0;

}

else

{

int one = numerator * obj.denominator;

int two = obj.numerator * denominator;

result = one - two;

}

return result;

}

  

  

/**

* Determines if two fractions are equal to each other

* @param obj

* @return true if the fractions are equal

*/

  

@Override

  

public boolean equals(Object obj)

{

boolean result = false;

if(this == obj)

{

result = true;

}

if ((obj == null) || (obj.getClass() != this.getClass()))

{

result = false;

}

Fraction otherFraction = (Fraction) obj;

this.lowestTerms();

this.adjustSign();

otherFraction.lowestTerms();

otherFraction.adjustSign();

if ((numerator == otherFraction.numerator) &&

(denominator == otherFraction.denominator));

{

result = true;

}

return result;

}

  

  

/**

* Converts a Fraction to a string

* @return string form of a fraction

*/

  

@Override

  

public String toString()

{

this.adjustSign();

this.lowestTerms();

return this.getNumerator() + "/" + this.getDenominator();

}

  

  

/**

* This method returns the value of the specified number as a int

* @return the value as an int

*/

  

@Override

  

public int intValue()

{

int i = denominator;

  

if (denominator == 0)

{

i = 0;

}

else

{

i = (int) numerator / denominator;

}

  

return i;

}

  

/**

* This method returns the value of the specified number as a long

* @return the value as a long

*/

  

@Override

  

public long longValue()

{

long i = denominator;

if (denominator == 0)

{

i = 0;

}

else

{

i = (long) numerator / denominator;

}

return i;

}

  

/**

* This method returns the value of the specified number as a float

* @return the value as a float

*/

  

@Override

  

public float floatValue()

{

float i = denominator;

if (denominator == 0)

{

i = 0;

}

else

{

i = (float) numerator / denominator;

}

return i;

}

  

/**

* This method returns the value of the specified number as a double

* @return the value as a double

*/

  

@Override

  

public double doubleValue()

{

double i = denominator;

if (denominator == 0)

{

i = 0;

}

else

{

i = (double) numerator / denominator;

}

return i;

}

}

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

Hi,

First of all, you have made lots of programming mistakes. It seems like your concepts are also not cleared. Let me start with the concepts first.

  • Here you need to create an Interface and then override it. It is inheritance. So first create an interface as

interface FractionInterface

{

// declare all methods over here like

void setNumerator(int n);

int getNumerator();

etc

}

  • You can not create an object of an Interface. Every method of an interface is abstract. Here you are creating an object of interface in sum, sub methods. Its completely wrong.
  • public Fraction (Fraction newFraction)
    {
    this.numerator = newFraction.numerator;
    this.denominator = newFraction.denominator;
    setFraction(numerator,denominator);
    }
    Here you are assigning the value of numerator and denominator in the first two statement then there is no use of method setFraction().and if you want to use setFraction method then you need to do just setFraction(newFraction.numerator,newFraction.denominator)
  • Wherever you want to return 0 as a fraction, please call parameterized constructor to create an object. You can also include 0 as a frcation. Create an object as
  • Fraction f = new Fraction(0,1); //where 0 is numerator and 1 is demoniator. That is ultimately 0 only.
  • In the adjustSign() function, you have write
  • else
    {
    return;
    }
    You have used return keyword. But the return type of your function is void. So it should never return any value. So never ever use return with void return type.
  • Your lowestTerm method
  • private void convertToLowestTerms()
    {
    int GCD = gcd(Math.abs(this.getNumerator()), Math.abs(this.getDenominator()));
    // calculates GCD of numerator and denominator
    int n = this.getNumerator() / GCD; // divides with GCD
    int d = this.getDenominator() / GCD;
    this.setFraction(n,d); //
    update current numerator and denominator value
    }
  • Here you have to convert your fraction into lowest terms so there is no need to create another fraction object. just update it eith a setFraction method.
  • One more thing dont call same method in each function. Just call it once. and update your value in fraction object. for eg. you are calling lowestFraction method in each function. its wrong way, because you have updated the value in object.
  • Just try your program with these many of changes, and still if you are getting any doubts then ask us.
Add a comment
Know the answer?
Add Answer to:
I need help with the following Java code Consider a class Fraction of fractions. Each fraction...
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
  • 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....

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

  • This is my code that i need to finish. In BoxRegion.java I have no idea how...

    This is my code that i need to finish. In BoxRegion.java I have no idea how to create the constructor. I tried to use super(x,y) but It is hard to apply. And Also In BoxRegionHashTable, I don't know how to create displayAnnotation BoxRegion.java ------------------------------------------------ public final class BoxRegion { final Point2D p1; final Point2D p2; /** * Create a new 3D point with given x, y and z values * * @param x1, y1 are the x,y coordinates for point...

  • C++ Fraction calculator Need help with code, cant use "using namespace std" Objectives Create and use...

    C++ Fraction calculator Need help with code, cant use "using namespace std" Objectives Create and use functions. Use a custom library and namespace. Use reference variables as parameters to return values from functions. Create a robust user interface with input error checking. Use exceptions to indicate errors. Resources kishio.h kishio.cpp Assignment requirements You will need eight methods (including main). One is given to you. Their requirements are specified below: menu: The menu function takes no arguments, but returns a char...

  • In C++ Fix any errors you had with HW5(Fraction class). Implement a function(s) to help with...

    In C++ Fix any errors you had with HW5(Fraction class). Implement a function(s) to help with Fraction addition. \**************Homework 5 code*****************************/ #include<iostream> using namespace std; class Fraction { private: int wholeNumber, numerator, denominator;    public: //get methods int getWholeNumber() { return wholeNumber; } int getNumerator() { return numerator; } int getDenominator() { return denominator; } Fraction()// default constructor { int w,n,d; cout<<"\nEnter whole number : "; cin>>w; cout<<"\nEnter numerator : "; cin>>n; cout<<"\nEnter denominator : "; cin>>d; while(d == 0)...

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

  • java only no c++ Write a Fraction class whose objects will represent fractions. You should provide...

    java only no c++ Write a Fraction class whose objects will represent fractions. You should provide the following class methods: Two constructors, a parameter-less constructor that assigns the value 0 to the Fraction, and a constructor that takes two parameters. The first parameter will represent the initial numerator of the Fraction, and the second parameter will represent the initial denominator of the Fraction. Arithmetic operations that add, subtract, multiply, and divide Fractions. These should be implemented as value returning methods...

  • In C# programming. Create a fractions class that represents fractions in the form a/b Your class...

    In C# programming. Create a fractions class that represents fractions in the form a/b Your class should implement the following members: int Numerator int Denominator Fraction(int numerator, int denominator) ­ creates a new Fraction double ToDecimal() ­ returns the fraction as a double Fraction Add(Fraction f) ­ adds the fraction to the one passed in and simplifies the result Fraction Multiply(Fraction f) ­ multiplies the fraction by the one passed in and simplifies the result Fraction Simplify() ­ simplifies the...

  • Consider the following code for a Fraction class: self. numerator = 0 self tsn return self. denominator # Greatest Common Divisor def GCD (self, m, n): while n != 0: m=t return m def reduce(self...

    Consider the following code for a Fraction class: self. numerator = 0 self tsn return self. denominator # Greatest Common Divisor def GCD (self, m, n): while n != 0: m=t return m def reduce(self): gcd - self.GCD(self._numerator, self._denominator) self. numerator int(self,_numerator / gcd) self'-denominator înt (self-denominator, gcd) def_str (self): 프 str(self-numerator). "ItDenominator, return "Numerator : str(self,-deno 프, . minator) Write a Unittest framework class to test the GCD method presented in the Fraction class Upload your answer code to...

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