Java Fraction Calculator

When you class mates tell you, that you didn’t call the reduce method, they mean, that you never use the reduce method.

Your add-method should look somewhat like this:

 public static String add(int n1, int n2, int d1, int d2) {
    int newn = (n1*d2) + (n2*d1);
    int newd = d1*d2;

    int divisor = reduce(newn, newd);
    newn/=divisor;
    newd/=divisor;
    int integerComponent=0;

    while(newn >= newd) {
        integerComponent++;
        newn-=newd;
    }
    String answer ="";
    if(integerComponent>0) {
        answer += integerComponent +"_";
    }
    if(newn!=0) {
        answer += newn+"/"+newd;
    }
    return answer;
}

and the multiply method should look like this:

public static String multiply(int n1, int n2, int d1, int d2) {
    int newn = n1*n2;
    int newd = d1*d2;

    int divisor = reduce(newn, newd);
    newn/=divisor;
    newd/=divisor;

    int integerComponent=0;

    while(newn >= newd) {
        integerComponent++;
        newn-=newd;
    }
    String answer ="";
    if(integerComponent>0) {
        answer += integerComponent +"_";
    }
    if(newn!=0) {
        answer += newn+"/"+newd;
    }
    return answer;
}

Remember that you also have to change your reduce method, as it always returns 1 right now!

Edit: Added code to print fraction as mixed fraction.

Leave a Comment