简单的对象和方法

时间:2016-03-13 03:52:29

标签: java object

程序是添加和平均并列出" addNumber"的次数。方法被调用。

我可以让Amount工作,但没有别的

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; 
}

我的错误输出:

金额:4 总和:4 平均值:0.0

2 个答案:

答案 0 :(得分:2)

好的,让我们从构造函数开始。

public NumberStatistics() {
this.amountOfNumbers=amountOfNumbers; 
this.average=0; 
this.sum=0;}

这里当你创建一个对象时,你将average和sum初始化为0但是 this.amountOfNumbers = amountOfNumbers;没有特别的影响。 总结我认为你想做的事情是这样的:

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;
}

然后我们在这里转到这段代码:

public void addNumber(int number) {
  number=addNumber; 
  addNumber++; 
}

好的,这行没有任何意义,因为你设置的参数等于addNumber变量,这对你来说根本没有帮助,我想你想做的是:

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

然后你需要一个返回平均值的方法:

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
}

最后,我认为您尝试创建的最后两种方法是:

public int amountOfNumbers() {
    return amountOfNumbers; 
}

public int sum() {
  return sum; 
}

这是我的第一篇文章,所以我希望它有所帮助。

答案 1 :(得分:1)

NumberStatistics中,您只需要countsum。您使用sum添加addNumber(并增加count)。像,

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();
    }
}