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

前端之家收集整理的这篇文章主要介绍了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;
    }

}
原文链接:https://www.f2er.com/java/437234.html

猜你在找的Java相关文章