Code for the method described in the question in java:
public static double averageRadius(MyCircle[] myCircles) {
double sum = 0;
for (MyCircle myCircle: myCircles) {
if(myCircle.getRadius() < 0) myCircle.setRadius(0);
sum += myCircle.getRadius();
}
return sum / myCircles.length;
}
And the complete program:
import java.util.Random;
public class MyCircle {
private double radius;
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public static double averageRadius(MyCircle[] myCircles) {
double sum = 0;
for (MyCircle myCircle: myCircles) {
if(myCircle.getRadius() < 0) myCircle.setRadius(0);
sum += myCircle.getRadius();
}
return sum / myCircles.length;
}
public static void main(String[] args) {
Random random = new Random();
int N = 10;
MyCircle[] myCircles = new MyCircle[N];
for (int i = 0; i < myCircles.length; i++) {
myCircles[i] = new MyCircle();
myCircles[i].setRadius(random.nextInt(100));
System.out.printf("Created MyCircle %d with radius %.2f \n", i, myCircles[i].getRadius());
}
System.out.printf("\nAverage radius of %d circles is %.2f \n", N, MyCircle.averageRadius(myCircles));
}
}
The output was:
Created MyCircle 0 with radius 76.00
Created MyCircle 1 with radius 86.00
Created MyCircle 2 with radius 38.00
Created MyCircle 3 with radius 4.00
Created MyCircle 4 with radius 8.00
Created MyCircle 5 with radius 39.00
Created MyCircle 6 with radius 77.00
Created MyCircle 7 with radius 78.00
Created MyCircle 8 with radius 39.00
Created MyCircle 9 with radius 46.00
Average radius of 10 circles is 49.10