One reason for writing methods is to divide up your code into manageable pieces. You test your program continually as you develop each method. if something goes wrong, you know where the problem is.
Another reason for writing a method is that it can be called several times
from different places in your program, which can save a lot of code. For
example, imagine extending the Count.java program to cope with all
digits, not just 0, 1, 2. The hundreds function might end up
looking like this:
// Convert a number h of hundreds into a phrase, where 0 < h <= 9.
String hundreds(int h)
{
String result;
if (h == 1) result = "one hundred";
else if (h == 2) result = "two hundred";
else if (h == 3) result = "three hundred";
else if (h == 4) result = "four hundred";
else if (h == 5) result = "five hundred";
else if (h == 6) result = "six hundred";
else if (h == 7) result = "seven hundred";
else if (h == 8) result = "eight hundred";
else if (h == 9) result = "nine hundred";
else result = "? hundred";
return result;
}
This function is doing almost exactly the same job as the units
function, but with a space and the word "hundred" stuck on the end. So,
instead of writing out (or copying-and-pasting) all those lines of code, we
could reuse the units function, like this:
// Convert a number h of hundreds into a phrase, where 0 < h <= 9.
String hundreds(int h)
{
return units(h) + " hundred";
}
Part of the art of writing methods is to make them as reusable as possible, not just in the current version of the program, but in future versions as it develops over time.