Java Reference
In-Depth Information
In both cases, a DecimalFormat object is created. The format of the object is specified
as input. Then the format method is called to format the output. Finally, the print or
println method needs to be called to display the result.
4.3 Code Refactoring
Methods have two main advantages. First, they make the code shorter by allowing us to
place repeating code inside a method and call the method when we want to execute the code.
Second, they allow us to break our program into modules and make it more manageable.
Let us reexamine the code for drawing a diamond of stars from the last chapter.
for ( int numStars =1, numSpaces = size 1; numSpaces > =0 ; numSpaces =2,
numStars+=2) {
for ( int i=0;i < numSpaces ;
i++)
{
System. out . print ( "" );
for ( int i=0;i < numStars ;
i++)
{
System. out . print ( "* " );
System. out . println () ;
for ( int numStars=size
>
2, numSpaces = 2; numStars
=0 ; numSpaces+=2,
{
for ( int i=0;i
numStars
=2 )
<
numSpaces ;
i++)
{
System. out . print ( "" );
for ( int i=0;i < numStars ;
i++)
{
System. out . print ( "* " );
System. out . println () ;
}
As you can see, the code for printing spaces and printing stars repeats twice. In order
to simplify the code, we will refactor it. Refactoring means restructuring the code without
changing its behavior. Of course, we can create a method that prints a number of stars and
a method that prints a number of spaces. An even better design would be to generalize the
task further and create a method that prints a bunch of characters. In other words, we want
to create a friend that can help us when we want to print characters. Unlike our friends
Peter and Bob, this friend will not charge us. A possible implementation of the method is
shown next.
public static void printStrings(String s , int n) {
for ( int i=0; i < n ; i ++) {
System. out . print ( s ) ;
}
}
Note that the method prints a number of strings instead of a number of characters
because we want to print the string “* ” multiple times. If we did not want to create a
space between the stars, then we could have created the following method.
public static void printChars( char c, int n) {
 
Search WWH ::




Custom Search