Java Reference
In-Depth Information
We've seen that methods can call other methods; this is equally true of methods
that take parameters. For example, here is a method for drawing a box of a given
height and width that calls the writeChars method:
public static void drawBox(int height, int width) {
// draw top of box
writeChars('*', width);
System.out.println();
// draw middle lines
for (int i = 1; i <= height - 2; i++) {
System.out.print('*');
writeChars(' ', width - 2);
System.out.println("*");
}
// draw bottom of box
writeChars('*', width);
System.out.println();
}
Notice that drawBox is passed values for its parameters called height and width
and that these parameters are used to form expressions that are passed as values to
writeChars . For example, inside the for loop we call writeChars asking it to pro-
duce width - 2 spaces. (We subtract 2 because we print a star at the beginning and
the end of the line.) Here is a sample call on the method:
drawBox(5, 10);
This code produces the following output:
**********
* *
* *
* *
**********
When you're writing methods that accept many parameters, the method header can
become very long. It is common to wrap long lines (ones that exceed roughly 80
characters in length) by inserting a line break after an operator or parameter and
indenting the line that follows by twice the normal indentation width:
// this method's header is too long, so we'll wrap it
public static void printTriangle(int xCoord1, int yCoord1,
int xCoord2, int yCoord2, int xCoord3, int yCoord3) {
...
}
 
Search WWH ::




Custom Search