Exploring Variable Length Parameter Lists The file Parameters.java contains a program to test the variable length method
Question:
Exploring Variable Length Parameter Lists
The fileParameters.javacontains a program to test the variable length methodaveragefrom Section 7.5 of the text. Note thataveragemust be a static method since it is called from the static methodmain.
- Compile and run the program.
- Add a call to find the average of a single integer, say 13. Print the result of the call.
- Add a call with an empty parameter list and print the result. Is the behavior what you expected?
- Add a methodmaximumthat takes a variable number of integer parameters and returns themaximumof the parameters. Invoke your method on each of the parameter lists used for the average function.
//*******************************************************
// Parameters.java
//
// Illustrates the concept of a variable parameter list.
//*******************************************************
import java.util.Scanner;s
public class Parameters
{
//-----------------------------------------------
// Calls the average method with
// different numbers of parameters.
//-----------------------------------------------
public static void main(String[] args)
{
double mean1, mean2;
mean1 = average(42, 69, 37);
mean2 = average(35, 43, 93, 23, 40, 21, 75);
System.out.println ("mean1 = " + mean1);
System.out.println ("mean2 = " + mean2);
}
//----------------------------------------------
// Returns the average of its parameters.
//----------------------------------------------
public static double average (int ... list)
{
double result = 0.0;
if (list.length != 0)
{
int sum = 0;
for (int num: list)
sum += num;
result = (double)sum / list.length;
}
return result;
}
}
Java How To Program Late Objects Version
ISBN: 9780136123712
8th Edition
Authors: Paul Deitel, Deitel & Associates