gpt4 book ai didi

java - 如何知道一个方法被主类调用了多少次?

转载 作者:搜寻专家 更新时间:2023-10-31 20:18:13 24 4
gpt4 key购买 nike

我的问题是找出从主类调用weight() 方法的次数。我应该在 totalWeightsMeasured() 方法中计算它。

代码的输出应该是 0,2,6。 (编辑//我早些时候在这里有 0,2,4 但输出实际上应该是 0,2,6)

但我只是不知道您如何计算它,我已经尝试用谷歌搜索和搜索所有内容,但我只是不知道该怎么做。 (并且您不应该再添加任何实例变量)

类:

public class Reformatory
{
private int weight;



public int weight(Person person)
{
int weight = person.getWeight();

// return the weight of the person
return weight;
}
public void feed(Person person)
{
//that increases the weight of its parameter by one.
person.setWeight(person.getWeight() + 1);

}
public int totalWeightsMeasured()
{


return 0;
}

}

主要内容:

public class Main
{

public static void main(String[] args)
{
Reformatory eastHelsinkiReformatory = new Reformatory();

Person brian = new Person("Brian", 1, 110, 7);
Person pekka = new Person("Pekka", 33, 176, 85);

System.out.println("total weights measured "+eastHelsinkiReformatory.totalWeightsMeasured());

eastHelsinkiReformatory.weight(brian);
eastHelsinkiReformatory.weight(pekka);

System.out.println("total weights measured "+eastHelsinkiReformatory.totalWeightsMeasured());

eastHelsinkiReformatory.weight(brian);
eastHelsinkiReformatory.weight(brian);
eastHelsinkiReformatory.weight(brian);
eastHelsinkiReformatory.weight(brian);

System.out.println("total weights measured "+eastHelsinkiReformatory.totalWeightsMeasured());
}
}

最佳答案

诀窍是使用尚未使用的现有实例变量权重作为计数器。

public class Reformatory
{
private int weight;

public int weight(Person person)
{
int weight = person.getWeight();

this.weight++;

// return the weight of the person
return weight;
}
public void feed(Person person)
{
//that increases the weight of its parameter by one.
person.setWeight(person.getWeight() + 1);

}
public int totalWeightsMeasured()
{
return weight;
}

}

关于java - 如何知道一个方法被主类调用了多少次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34039473/

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