Computer Science 15-100 (Sections T & U), Fall 2007
Class Notes:   Writing Classes (1 of 2)


Logistics

  1. Reading:  L&L Sections Chapter 4

Today in class we wrote a simple class from scratch that supported basic operations over rational numbers.  We only implemented "times" and "reduce" in class.  Here is the code from class:

// This code was developed in class, so it does not have great style, etc...

public class RationalDemo {
  public static void main(String[] args) {
    Rational r1 = new Rational(2,3);
    Rational r2 = new Rational(3,7);
    Rational r3 = r1.times(r2);
    // r1.print();
    // r2.print();
    // r3.print();
    System.out.println(r1 + " * " + r2 + " = " + r3);
  }
}

class Rational {
  public void print() {
    System.out.println("Hi, my value is " + this.toString());
  }
  
  public Rational reduce() {
    int newNum = this.num;
    int newDen = this.den;
    for (int f=Math.min(newNum,newDen); f>=2; f--)
      if ((newNum % f == 0) && (newDen % f == 0)) {
         newNum /= f;
         newDen /= f;
      }
    return new Rational(newNum,newDen);
  }
    
  public Rational times(Rational that) {
    int num = this.num * that.num;
    int den = this.den * that.den;
    Rational result = new Rational(num,den);
    return result.reduce();
  }
  
  // public static Rational constructor(int num, int den) {
  public Rational(int n, int d) {
    num = n;
    den = d;
  }
  
  private int num;
  private int den;
  
  public String toString() {
    return num + "/" + den;
  }
}

Carpe diem!