java – 如何知道从主类调用方法的次数?

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

代码输出应为0,2,6. (编辑//我之前在这里0,4,但输出应该是0,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;
    }

}

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...