gpt4 book ai didi

java - 简单的对象和方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:39:23 25 4
gpt4 key购买 nike

程序是添加和平均并列出调用“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

最佳答案

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

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

在这里,当你创建一个对象时,你将 average 和 sum 初始化为 0 但是this.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;
}

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

关于java - 简单的对象和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35966255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com