Java Reference
In-Depth Information
double arguments as the caller passes. The output shows that each call to method average
returns the correct value.
Common Programming Error 7.5
Placing an ellipsis indicating a variable-length argument list in the middle of a parameter
list is a syntax error. An ellipsis may be placed only at the end of the parameter list.
1
// Fig. 7.20: VarargsTest.java
2
// Using variable-length argument lists.
3
4
public class VarargsTest
5
{
6
// calculate average
7
public static double average(
double ... numbers
)
8
{
9
double total = 0.0 ;
10
11
// calculate total using the enhanced for statement
12
for ( double d : numbers)
total += d;
13
14
15
numbers.length
return total /
;
16
}
17
18
public static void main(String[] args)
19
{
20
double d1 = 10.0 ;
21
double d2 = 20.0 ;
22
double d3 = 30.0 ;
23
double d4 = 40.0 ;
24
25
System.out.printf( "d1 = %.1f%nd2 = %.1f%nd3 = %.1f%nd4 = %.1f%n%n" ,
26
d1, d2, d3, d4);
27
28
System.out.printf( "Average of d1 and d2 is %.1f%n" ,
29
average(d1, d2)
);
30
System.out.printf( "Average of d1, d2 and d3 is %.1f%n" ,
31
average(d1, d2, d3)
);
32
System.out.printf( "Average of d1, d2, d3 and d4 is %.1f%n" ,
33
average(d1, d2, d3, d4)
);
34
}
35
} // end class VarargsTest
d1 = 10.0
d2 = 20.0
d3 = 30.0
d4 = 40.0
Average of d1 and d2 is 15.0
Average of d1, d2 and d3 is 20.0
Average of d1, d2, d3 and d4 is 25.0
Fig. 7.20 | Using variable-length argument lists.
Search WWH ::




Custom Search