加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 01:04:27 所属栏目:Java 来源:网络整理
导读:我的问题是找出从主类调用weight()方法的次数.我应该在totalWeightsMeasured()方法中计算它. 代码的输出应为0,2,6. (编辑//我之前在这里0,4,但输出应该是0,6) 但我只是不知道你怎么能计算它,我试图谷歌和一切,但我只是不知道该怎么做. (并且您不应该再添加任

我的问题是找出从主类调用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;
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读