Lab 4 (July 1)

In-Lab Assignment 2

Today in lab you will create a package and use it, then turn in your source code. The assignment is due at the end of the next lab, which for this time of the year means Thursday July 8. You can, of course, turn it in earlier if you want.

Create a username.Math package and put class Fraction in it. Take the code from the lecture notes and add one constructor that supports the creation of Fraction objects that are already integers that is, their denominator is 1. Then write a small test program that imports the package, creates a few objects of type Fraction and works with them.

Note: please don't forget to make the Fraction class public so that it can be accessed from outside your Math package.

Here's basically how I created my package:

tucotuco.cs.indiana.edu% vi Fraction.java
tucotuco.cs.indiana.edu% ls -l
total 6
-rw-r--r--   1 dgerman  students    2159 Jul  1 11:36 Fraction.java
tucotuco.cs.indiana.edu% javac -d . Fraction.java
tucotuco.cs.indiana.edu% du -a
6       ./Fraction.java
4       ./dgerman/Math/Fraction.class
6       ./dgerman/Math
8       ./dgerman
16      .
Then I place the source code for Fraction.java in a directory of sources.

tucotuco.cs.indiana.edu% mkdir sources      
tucotuco.cs.indiana.edu% mv Fraction.java sources
And here's how I test it:
tucotuco.cs.indiana.edu% pico Tester.java
tucotuco.cs.indiana.edu% cat Tester.java
import dgerman.Math.*;
 
class Tester {
  public static void main(String[] args) {
    Fraction a = new Fraction(3, 4); 
    Fraction b = new Fraction(5);
    System.out.println( a + " + " + b + " = " + a.plus(b)); 
    System.out.println("(1/3 + 2) * (3/4)= " + 
      ((new Fraction(1, 3)).plus(new Fraction(2))).times(new Fraction(3, 4))
    ); 
  } 
} 
tucotuco.cs.indiana.edu% javac Tester.java
tucotuco.cs.indiana.edu% ls -l
total 10
-rw-r--r--   1 dgerman  students    1051 Jul  1 11:49 Tester.class
-rw-r--r--   1 dgerman  students     356 Jul  1 11:47 Tester.java
drwxr-x--x   3 dgerman  students     512 Jul  1 11:36 dgerman
drwxr-xr-x   2 dgerman  students     512 Jul  1 11:49 sources
tucotuco.cs.indiana.edu% java Tester
3/4  + 5/1  = 23/4 
(1/3 + 2) * (3/4)= 7/4 
tucotuco.cs.indiana.edu%
Notice (in Tester) that I added the new constructor to class Fraction and you that you should add it to your Fraction class, too. (Hint: use this() to invoke the already existing constructor).