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

代码的输出应为0、2、6。 (编辑//我之前在这里有0,2,4,但输出实际上应该是0,2,6)

但是我只是不知道如何计算,我已经尝试使用Google和其他工具,但我只是不知道该怎么做。 (和,您不应再添加任何实例变量)

类(class):

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/

10-11 22:47
查看更多