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 projectRecursionOnNaturalNumber1. - Open the
srcfolder of this project and then open(default package). As a starting point you can use any of the Java files. Rename itNaturalNumberStaticOpsand 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.javafile; 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
decrementstatic method using only theNaturalNumberKernelmethods (multiplyBy10,divideBy10, andisZero). The code forincrementis provided as an example of a recursive method onNaturalNumber. - Run the program and test your implementation of
decrement. - Complete the body of the
printWithCommasstatic method. This method outputs the givenNaturalNumberto 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 theNaturalNumbermethods. Note that the contract for this method states (implicitly) that the value of the givenNaturalNumbermust 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
toStringWithCommasstatic method. This method is similar toprintWithCommas, except that instead of printing the number with commas to an output stream, it returns aStringrepresentation of the number with commas. - Run the program and test your implementation of
toStringWithCommas.