Question
Exploring Variable Length Parameter Lists The file Parameters.java contains a program to test the variable length method average from Section 7.5 of the text. Note
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;
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started