JAVA: AverageCalculator Class Write a class AverageCalculator. The purpose of a
ID: 3666056 • Letter: J
Question
JAVA:
AverageCalculator Class
Write a class AverageCalculator. The purpose of a AverageCalculator object is to count, sum and average a series of numbers. The AverageCalculator class has the following specification:
// instance variable of type int for the running total of numbers that have been given to the AverageCalculator
// instance variable of type int for the count of numbers that have been given to the AverageCalculator
// default constructor
AverageCalculator ()
// Mutator to add a number to the AverageCalculator
void add(int newNum)
// Accessor to return the sum of all the numbers added to the AverageCalculator
int getSum()
// Accessor to return the count, or number, of numbers added to the AverageCalculator
int getCount()
// Accessor to return the average of all the numbers added to the AverageCalculator
// note that the instance variables are int, and the return type of this method is double--be careful with the division operation double getAverage()
Write a class, AverageCalculatorMain that contains a main method and does the following:
~ create a AverageCalculator object, add one number to the AverageCalculator (pick whatever value you wish), and print the sum, count and average of the AverageCalculator .
~create another AverageCalculator object. Add three numbers to the AverageCalculator , and print the sum, count and average of the AverageCalculator .
Thank you!
Explanation / Answer
package com.he.capillary;
public class AverageCalculator {
private int count;
private int sum;
AverageCalculator() {
}
double getAverage() {
return sum*1.0 / count * 1.0;
}
void add(int newNum) {
this.sum += newNum;
this.count += 1;
}
int getSum() {
return this.sum;
}
int getCount() {
return this.count;
}
}
package com.he.capillary;
public class AverageCalculatorMain {
public static void main(String[] args) {
AverageCalculator ac = new AverageCalculator();
ac.add(100);
ac.add(25);
ac.add(25);
ac.add(25);
System.out.println(ac.getAverage()+" "+ac.getCount()+" "+ac.getSum());
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.