Lab: Recursion on NaturalNumber – Static Methods
Objective
In this lab you will practice recursion on NaturalNumbers
by implementing the decrement and printWithCommas
static methods.
Setup
Follow these steps to set up a project for this lab.
- Create a new Eclipse project by copying ProjectTemplate.
Name the new project RecursionOnNaturalNumber1.
- Open the src folder of this project and then open
(default package). As a starting point you can use any of
the Java files. Rename it NaturalNumberStaticOps and
delete the other files from the project.
- Follow the link to NaturalNumberStaticOps.java,
select all the code on that page (click and hold the left mouse
button at the start of the program and drag the mouse to the end
of the program) and copy it to the clipboard (right-click the
mouse on the selection and choose Copy from the contextual
pop-up menu), then come back to this page and continue with these
instructions.
- Finally in Eclipse, open the NaturalNumberStaticOps.java file;
select all the code in the editor, right-click on it and select Paste
from the contextual pop-up menu to replace the existing code with
the code you copied in the previous step. Save your file.
Method
- Complete the body of the decrement static method
using only the NaturalNumberKernel
methods (multiplyBy10, divideBy10, and isZero).
The code for increment is provided as an example of a
recursive method on NaturalNumber.
- Run the program and test your implementation of decrement.
- Complete the body of the printWithCommas static
method. This method outputs the given NaturalNumber to an
output stream, inserting a comma before every group of three
digits (from right to left). So the number 12345678 would be
printed as 12,345,678. For this method you can use any of the NaturalNumber
methods. Note that the contract for this method states
(implicitly) that the value of the given NaturalNumber
must be restored so that the outgoing value of n is
the same as the incoming value.
- Run the program and test your implementation of printWithCommas.
Additional Activities
- Complete the body of the toStringWithCommas static
method. This method is similar to printWithCommas, except
that instead of printing the number with commas to an output
stream, it returns a String representation of the number
with commas.
- Run the program and test your implementation of toStringWithCommas.