Next: Another constructor
Up: Assignment 0: User-defined objects
Previous: BigIntegers
A rational number is a number that can be represented as the ratio of
two integers. For example, 2/3 is a rational number, and you can
think of 7 as a rational number with an implicit 1 in the denominator.
For this assignment, you are going to write a class definition for
rational numbers.
- Create a directory called Complex. Go to
http://rocky.wellesley.edu/cs230/code/hw00
and download the files Test.java and Complex.java.
Put them in the new directory. Compile and run them using a
command like:
javac Test.java Complex.java; java Test
We have to compile all the files, but when we run the program
we only need to specify the startup class.
Print a copy of both files and make sure you understand how they work.
You should use this example as a template for what follows.
- Create a new directory named Rational with files
called Rational.java and Test.java.
- The Rational class should have two integers as instance
variables; they will contain the numerator and denominator of each
Rational object.
- Write a constructor that takes no arguments and that sets the
two instance variables to zero.
- Write a method called printRational that takes
a Rational object as an argument and prints it in some
reasonable format.
- Write a main method in Test that creates a new
object with type Rational, sets its instance variables to some values,
and prints the object.
- At this stage, you have a minimal testable (debuggable)
program. Debug it. Whenever I start writing a new class,
I start with these three steps: instance variables, a simple
constructor, and a print method. Then I add methods and test
them one at a time.
Allen Downey
Thu Sep 7 11:50:06 EDT 2000