# fraction class

• 05-06-2013, 08:30 PM
ericgomez7
fraction class
/**
* What is wrong with my multiplication and division methods?
*/

public class Fraction
{

// instance variables (fields) of our Fraction object
public int num;
public int denom;

// **** Constructors for Fraction Objects ****

public Fraction(int n, int d)
{
num = n;
denom = d;
cleanup();
}

// **** Public Methods for Fraction Objects ****
public String toString()
{
return num + "/" + denom;
// add code to print out mixed fraction
}

{
int commonDenom = denom * other.denom;
int numerator = num*other.denom + other.num * denom;
return new Fraction(numerator,commonDenom);

} // end of add method

// **** Private Methods for Fraction Objects ****
private void cleanup()
{
if (denom < 0)
{
num *= -1;
denom *= -1;
}

// reduce the fraction by finding gcf
int factor = gcf(Math.abs(num),Math.abs(denom));
num = num/factor;
denom = denom/factor;
}

// Returns the greatest common factor
// of two positive integers
private int gcf(int n, int d)
{

if (n % d == 0)
return d;
else if (d % n == 0)
return n;
else
return gcf(n % d, d % n);
} // end of gcf method

public Fraction subtract(Fraction other) {
int commonDenom2 = denom * other.denom;
int numerator2 = num*other.denom - other.num * denom;
return new Fraction(numerator2,commonDenom2);

}

public Fraction multiply(Fraction other) {
int commonDenom3 = denom * other.denom;
int numerator3 = num*other.denom * other.num * denom;
return new Fraction(numerator3,commonDenom3);

}

public Fraction divide(Fraction other) {
int commonDenom4 = denom * other.denom;
int numerator4 = num*other.denom / other.num * denom;
return new Fraction(numerator4,commonDenom4);
}

} // end of Fraction class
• 05-06-2013, 09:36 PM
JosAH
Re: fraction class
(a/b)*(c/d) == (a*c)/(b*d) and (a/b)/(c/d) == (a*d)/(b*c)

kind regards,

Jos