Reputation: 123
Program is to add and average and list amount of times the "addNumber" method is called.
I can make the Amount work, but nothing else
public class Main {
public static void main(String[] args) {
NumberStatistics stats = new NumberStatistics();
stats.addNumber(3);
stats.addNumber(5);
stats.addNumber(1);
stats.addNumber(2);
System.out.println("Amount: " + stats.amountOfNumbers());
System.out.println("sum: " + stats.sum());
System.out.println("average: " + stats.average());
}
public class NumberStatistics {
private int amountOfNumbers;
private int addNumber;
private double average;
private int sum;
public NumberStatistics() {
this.amountOfNumbers=amountOfNumbers;
this.average=0;
this.sum=0;
}
public void addNumber(int number) {
number=addNumber;
addNumber++;
// code here
}
public int amountOfNumbers() {
return addNumber;
// code , here
}
public int sum() {
return this.addNumber++;
}
public double average() {
return sum() / addNumber;
}
My incorrect output:
Amount: 4 sum: 4 average: 0.0
Upvotes: 3
Views: 372
Reputation: 743
Ok lets start with the constructor.
public NumberStatistics() {
this.amountOfNumbers=amountOfNumbers;
this.average=0;
this.sum=0;}
Here when you create an object you initialize average and sum to 0 but this.amountOfNumbers=amountOfNumbers; has no particular effect. To sum up what i think you wanted to do is something like this:
public NumberStatistics()
{
this.average = 0;//this keyword here is not needed but i used it since you did too
this.sum = 0;
this.amountOfNumbers = 0;
}
Then we go to this block of code here:
public void addNumber(int number) {
number=addNumber;
addNumber++;
}
Ok, this line makes no sense since you are setting the parameter equal to the addNumber variable which is something that does not help you at all, what i think you wanted to do here is the following:
public void addNumber(int number) {
sum += number;//same as sum = sum + number;
amountOfNumbers++;//same as amountOfNumbers = amountOfNumbers +1;
}
Then you need a method that returns the average like this:
public double average() {
return average = sum / amountOfNumbers; //i use the average variable only because you did,
//the most efficient way here is just to return sum / amountOfNumbers
}
Finally, the last two methods that i think you were trying to create are these:
public int amountOfNumbers() {
return amountOfNumbers;
}
public int sum() {
return sum;
}
This is my first post ever so i hope that it helps.
Upvotes: 2
Reputation: 201439
In NumberStatistics
, you only need the count
and a sum
. You add to the sum
with addNumber
(and increment the count
). Something like,
public class NumberStatistics {
private int count = 0;
private int sum = 0;
public void addNumber(int number) {
this.sum += number;
count++;
}
public int getCount() {
return count;
}
public int sum() {
return sum;
}
public double average() {
return sum() / (double) getCount();
}
}
Upvotes: 1