Nebular Nebular - 5 months ago 11
Java Question

simple objects and methods

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

Answer

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 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 here this line makes no sense because you are setting the parameter equal to the addNumber variable which is something that does not help you at all, what i think you want to do here is

public void addNumber(int number) {
   sum += number;//same as sum = sum + number; 
   amountOfNumbers++;//same as amountOfNumbers = amountOfNumbers +1;
}

Then you need a method that returs 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
}

Finaly 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.

Comments