Java Reference
In-Depth Information
}
}
public static void
printLine(
int
numSpaces ,
int
numStars)
{
printStrings(
""
, numSpaces) ;
printStrings(
"* "
, numStars) ;
System. out . println (
""
);
}
public static void
main(String [] args)
{
Scanner keyboard =
new
Scanner(System. in) ;
System. out . print (
"Enter size of diamond: "
);
int
size = keyboard.nextInt() ;
for
(
int
numStars = 1 , numSpaces = s i ze
−
1; numSpaces
>
=0;
numSpaces
−
= 2 , numStars += 2)
{
printLine (numSpaces , numStars ) ;
for
(
int
numStars = size
−
2 , numSpaces = 2; numStars
>
=0;
numSpaces += 2 , numStars
−
=2)
{
printLine (numSpaces , numStars ) ;
}
}
}
Now the code is much easier to understand. If we look at the code, we will see that we
first print a bunch of lines with stars, where every time the number of stars increases by
two. Then, we print a bunch of lines, where every time the number of stars decreases by two.
One may even be able to guess that we are printing a diamond just by examining the code.
This code is an example of
self-documenting
code. The above example shows the importance
of giving appropriate names to methods and variables. It also shows how creating compact
methods that perform a single task can make the code easier to write, understand, and
modify.
4.4 Documenting Methods Using JavaDoc
Note that after you type: “
printLine(
” in your program in NetBeans, you can press
Ctrl+Space
for auto-completion. NetBeans will show you that there is a method that takes
as input two variables of type
int
and the name of the variables. However, it will not give
you any additional information and it will show
JavaDoc missing
. Conversely, if you type
“
printf(
” and press Ctrl+Space, then you will see a detailed description of the method.
The reason is that someone went through the trouble of writing documentation for the
printf
method. It will be nice if we can do the same for the methods that we write.
JavaDoc
is the de facto standard for documenting Java code. It allows the automatic
creation of web pages (i.e., HTML files) that describe the methods of a program. For
example, type in your favorite search engine: “Java Scanner”. Select the first answer. It
will take you to a web page that describes the
Scanner
class and its methods. Believe it
or not, this page is automatically created from JavaDoc. Whoever wrote the
Scanner
class
used JavaDoc to document their code. Then they compiled the code into an HTML file and
posted it on the Internet.
Let us go back to our example of printing a diamond. Type
/**
on a separate line
immediately before the
printStrings
method. Press
Enter
on the keyboard. The following
template will be automatically generated by NetBeans.