Question:
Consider the following method signature in Java:
public static void analyzeData(double[] data) {
// implementation goes here
}
You are required to implement the analyzeData()
method that performs the following tasks:
data
array, rounded to 2 decimal places.data
array.data
array.data
array that are greater than or equal to the average value.Write the complete implementation of the analyzeData()
method, including the necessary operations to accomplish the given tasks. Your code should adhere to the following requirements:
data
array will always have at least one element.Average value: X.XX
Minimum value: X.XX
Maximum value: X.XX
Count of values greater than or equal to the average: X
Example:
For the input array data = {3.2, 1.5, 4.8, 2.6, 3.9}
, the expected output is:
Average value: 3.20
Minimum value: 1.50
Maximum value: 4.80
Count of values greater than or equal to the average: 3
Provide your solution below:
public static void analyzeData(double[] data) {
double sum = 0;
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for (double d : data) {
sum += d;
if (d < min) {
min = d;
}
if (d > max) {
max = d;
}
}
double average = sum / data.length;
int count = 0;
for (double d : data) {
if (d >= average) {
count++;
}
}
System.out.printf("Average value: %.2f\n", average);
System.out.printf("Minimum value: %.2f\n", min);
System.out.printf("Maximum value: %.2f\n", max);
System.out.println("Count of values greater than or equal to the average: " + count);
}
Explanation:
We start by initializing variables sum
, min
, and max
. sum
will be used to calculate the sum of all elements, while min
and max
will store the minimum and maximum values encountered so far. We initialize min
with Double.MAX_VALUE
, which is the highest possible value for a double
, and max
with Double.MIN_VALUE
, which is the lowest possible value for a double
.
We iterate over the elements in the data
array using a for-each loop. For each element d
, we add it to the sum
and update the values of min
and max
if necessary.
After the loop, we calculate the average by dividing the sum
by the length of the data
array.
We then iterate over the elements in the data
array again, counting the number of elements that are greater than or equal to the average.
Finally, we use System.out.printf()
to print the average, minimum, and maximum values with 2 decimal places. The count value is printed directly using System.out.println()
.
Note: The code uses the printf()
method for formatted output. The format specifier %.2f
is used to specify that the corresponding argument should be printed as a floating-point value with 2 decimal places.