Exercise 5: Arrays and Loops

Create a directory for this exercise and download MeanValue.java into it. This file contains the skeleton of a small program to compute the arithmetic mean of a set of numerical values, supplied via the command line. Your task is to add the missing code to this skeleton.

In the static method meanValue(), write code that will compute the mean of the double values supplied via the array parameter data. You can assume that the array always contains at least one value. The result of computation should be returned by the method.

In main(), write code that uses the meanValue() method to compute the mean of values supplied on the command line. Note that args, which holds the command line arguments, is an array of strings. You will therefore need to create another array, holding the equivalent double values.

The mean of the supplied values should be displayed to three decimal places of accuracy, using System.out.printf(). If no values have been supplied, the program should display a usage message via System.err and then terminate with a non-zero exit status.

Here are examples of expected program behaviour:

$ java MeanValue 1.2 0.7 4.3
Mean value = 2.067
$ java MeanValue
Usage: java MeanValue <values...>

Tips