Tuesday, June 21, 2005

Fraction Class

Today, I read some help request on writting a Fraction class, It is pretty suprise to me that the requester doesn't understand the requirement of the class, but the more ridiculous isszue that shocked me its that someone say:

"if u are in deep trouble understanding the above, you may consider pm me to get the code for some cost"

How bullshit it is !!!!

IMHO forumer should help each other with free and respect. it is meanless that these guys help only the people who pay their money. This lose the meaning of forum it lose the spirite comunity. ..

Any way here is source code of Fraction class:

public class Fraction {

final int numerator;

final int denominator;

public static final Fraction ZeroFraction = new Fraction(0, 0);

public Fraction(int numerator, int denominator)
throws IllegalArgumentException {
if (denominator == 0) {
throw new ArithmeticException("Divide by zero");
}
int simplier = Fraction.simplify(numerator, denominator);
this.numerator = numerator / simplier;
this.denominator = denominator / simplier;
}

public int getDenominator() {
return denominator;
}

public int getNumerator() {
return numerator;
}

public double toDouble() {
return numerator / denominator;
}

public String toString() {
return numerator + "/" + denominator;
}

/* a/ b + c / d = (ad + bc) / bd */
public Fraction add(Fraction f1, Fraction f2) {
int newNumerator = f1.numerator * f2.denominator + f1.denominator
* f2.numerator;
int newDenominator = (f1.denominator * f2.denominator);
return new Fraction(newNumerator, newDenominator);
}

/* a/ b - c / d = (ad - bc) / bd */
public Fraction subtract(Fraction f1, Fraction f2) {
int newNumerator = f1.numerator * f2.denominator - f1.denominator
* f2.numerator;
int newDenominator = (f1.denominator * f2.denominator);
return new Fraction(newNumerator, newDenominator);
}

/* a/ b x c / d = ac / bd */
public Fraction multiply(Fraction f1, Fraction f2) {
int newNumerator = f1.numerator * f2.numerator;
int newDenominator = f1.denominator * f2.denominator;
return new Fraction(newNumerator, newDenominator);
}

/* (a/ b )/ (c / d) = ad /bc , where c/d not equal to 0 */
public Fraction divide(Fraction f1, Fraction f2) {
if (f2.toDouble() == 0) {
throw new ArithmeticException("Divide by zero");
}
int newNumerator = f1.numerator * f2.denominator;
int newDenominator = f1.denominator * f2.numerator;
return new Fraction(newNumerator, newDenominator);
}

private static int simplify(int a, int b) {
if (a % b > 0)
return simplify(b, a % b);
else
return b;
}

public static void main(String[] args) {
// TODO Auto-generated method stub

}

}

No comments: