Next: Make your program even
Up: Programming assignment
Previous: Print the date
A much more sensible way to proceed is to make your code into a method.
That way you can have one copy of the code and invoke it several times
with different arguments each time.
- 1.
- After the declaration of main, create a new method
definition. It will look a lot like the definition of main,
except that the name will be printOrdinal and the arguments
will be different. It should look like:
public static void printOrdinal (int x) {
// put your code here
}
- 2.
- For now, you can ignore the words public and static,
but you should know that void means that this method does not
return anything, that printOrdinal is the name of the method,
and that (int x) means that this method takes a single argument
named x that has type int.
IMPORTANT: Don't forget the word static. If you leave it out,
you will get a mystifying error message. As a matter of fact, you
should go ahead and do it on purpose, just so you see what the error
message is. Then if you do it by accident, you'll know what it means.
- 3.
- Move your code from main into the body of the new method.
You will have to make a couple of changes. For example, you should
not set the value of x in printOrdinal -- you will
receive it as an argument from main.
- 4.
- Modify main to invoke printOrdinal twice, printing
``The 13th day of the 7th month'' just like it did before.
Other than being shorter, what advantages does this program have
over the previous version?
Next: Make your program even
Up: Programming assignment
Previous: Print the date
Allen B. Downey
2/18/1998