Sample Class - Fraction

Fraction.java
//
//  Fraction class
//
//  methods:
//      constructors
//      add               returns the sum of parm and invoking object
//      multiply          returns the product of parm and invoking object
//      printFrac         prints a Fraction
//

import java.io.PrintWriter;

public class Fraction {

    private int num;            //  numerator
    private int denom;          //  denominator

//      initialize the Fraction to zero if no args are passed

    public Fraction() {
        num = 0;
        denom = 1;
    }

//      initialize the Fraction to the given integer

    public Fraction(int whole) {
        num = whole;
        denom = 1;
    }

//      initialize the Fraction with the given numerator and denominator

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

//      multiply the invoking object by the parameter and return
//      the product. the result is not reduced

    public Fraction mult(Fraction multit) {
        Fraction product = new Fraction();
        product.num = num * multit.num;
        product.denom = denom * multit.denom;
        return product;
    }

//      add the invoking object and the parameter and return
//      the sum. the result is not reduced

    public Fraction add(Fraction addit) {
        Fraction sum = new Fraction();
        int newdenom = denom * addit.denom;
        sum.denom = newdenom;
        sum.num = num * addit.denom + addit.num * denom;
        return sum;
    }

//      print a Fraction to the given output device

    public void printFrac(PrintWriter outdev) {
        outdev.print(num + "/" + denom);
    }

}




FractionTest.java

//////////////////////////////////////////////////////////////////////////////
//
//  class FractionTest
//
//      main function to test the Fraction class
//

import java.io.PrintWriter;

class FractionTest {

    public static void main(String[] args) {
        PrintWriter stdout = new PrintWriter(System.out,true);
        Fraction first = new Fraction(1,2);
        Fraction second = new Fraction(3,2);
        Fraction third;
        Fraction fourth;

        third = first.mult(second);
        stdout.print("The product is: ");
        third.printFrac(stdout);
        stdout.println();
        fourth = first.add(second);
        stdout.print("The sum is: ");
        fourth.printFrac(stdout);
        stdout.println();
    }
}

Output:
The product is:  3/4
The sum is:  8/4


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page