The following assignment relates to arrays and (naturally) objects. Using the at
ID: 3837941 • Letter: T
Question
The following assignment relates to arrays and (naturally) objects. Using the attached Circle class as a reference (feel free to use this class!), pleae write an application that performs the following:
Step 1: create a Circle array that holds 1000 Circle objects
Step 2: using a for loop, initialize the Circle array - create 1000 Circle objects and store each Circle object in the array. (Hint : use the index of the array as the argument for the Circle constructor)
Step 3. Create a method that accepts A Circle array (see step 2) , and returns the sum of all Circle objects in the array.
Step 4. Create a method that accepts a Circle array (see step 2) and returns the average area of all Circle objects in the array.
Step 5. Call the methods in steps 3 and 4 to display the values returned by those methods.
Explanation / Answer
class Circle{
private double radius;
public Circle(double radius) {
this.setRadius(radius);
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double area(){
return (22.0/7.0)*radius*radius;
}
}
public class CircleArrayDemo {
public static void main(String[] args) {
Circle circles[] = new Circle[1000];
for(int i=0; i<circles.length; i++){
circles[i] = new Circle(i);
}
System.out.println("Sum ="+getSum(circles));
System.out.println("Average ="+getAverage(circles));
}
public static long getSum(Circle[] circles){
long sum=0;
for(int i=0; i<circles.length; i++){
sum += circles[i].area();
}
return sum;
}
public static double getAverage(Circle[] circles){
double sum=0.0;
for(int i=0; i<circles.length; i++){
sum += circles[i].area();
}
return sum/(double)circles.length;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.