Write a class Array with a constructor and two methods: Array(double[] array): c
ID: 640693 • Letter: W
Question
Write a class Array with a constructor and two methods: Array(double[] array): constructor that stores array into a member variable (field). double sum(): computes the sum of the elements stored in the array. double average(): computes the average of the elements stored in the array. Make sure your methods handles the case of an empty array (an array with no elements) or a null array by returning a 0. You may use your main method for testing, but it will not be tested by webcat.
So far I have this:
public class Array {
double[] array;
Array(double[] array) {
this.array = array;
}
double sum() {
int sum = 0;
for (int i = 0; i < array.length; i++){
sum += array[i];
}
if (array == null){
return 0;
}
return sum;
}
double average() {
int average = 0;
if (array.length > 0) {
return sum() / array.length;
}
if (array == null){
return 0;
}
return average;
}
public static void main(String[] args) {
double[] a = {1.0, 2.0, 3.0};
Array array = new Array(a);
System.out.printf("sum = %f ", array.sum());
System.out.printf("avg = %.3f ", array.average());
}
}
The code compiles and seems to work but when I upload it I get this feedback:
average null array
sum(): check when there is only one element in the array
sum null array
Explanation / Answer
class Array {
double[] array;
Array(double[] array) {
this.array = array;
}
double sum() {
double sum = 0;
if (array == null){
return 0;
}
for (int i = 0; i < array.length; i++){
sum += array[i];
}
return sum;
}
double average() {
double average = 0;
if (array == null){
return 0;
}
if (array.length > 0) {
average = sum() / array.length;
}
return average;
}
public static void main(String[] args) {
double[] a = {1.0, 2.0, 3.0};
double[] b = {25.0};
Array array = new Array(b);
System.out.printf("sum = %f ", array.sum());
System.out.printf("avg = %.3f ", array.average());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.