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

前端之家收集整理的这篇文章主要介绍了java – 如何知道从主类调用方法的次数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

代码输出应为0,2,6. (编辑//我之前在这里0,4,但输出应该是0,6)

但我只是不知道你怎么能计算它,我试图谷歌和一切,但我只是不知道该怎么做. (并且您不应该再添加任何实例变量)

类:

  1. public class Reformatory
  2. {
  3. private int weight;
  4. public int weight(Person person)
  5. {
  6. int weight = person.getWeight();
  7. // return the weight of the person
  8. return weight;
  9. }
  10. public void Feed(Person person)
  11. {
  12. //that increases the weight of its parameter by one.
  13. person.setWeight(person.getWeight() + 1);
  14. }
  15. public int totalWeightsMeasured()
  16. {
  17. return 0;
  18. }
  19. }

主要:

  1. public class Main
  2. {
  3. public static void main(String[] args)
  4. {
  5. Reformatory eastHelsinkiReformatory = new Reformatory();
  6. Person brian = new Person("Brian",1,110,7);
  7. Person pekka = new Person("Pekka",33,176,85);
  8. System.out.println("total weights measured "+eastHelsinkiReformatory.totalWeightsMeasured());
  9. eastHelsinkiReformatory.weight(brian);
  10. eastHelsinkiReformatory.weight(pekka);
  11. System.out.println("total weights measured "+eastHelsinkiReformatory.totalWeightsMeasured());
  12. eastHelsinkiReformatory.weight(brian);
  13. eastHelsinkiReformatory.weight(brian);
  14. eastHelsinkiReformatory.weight(brian);
  15. eastHelsinkiReformatory.weight(brian);
  16. System.out.println("total weights measured "+eastHelsinkiReformatory.totalWeightsMeasured());
  17. }
  18. }
最佳答案
诀窍是使用现有的实例变量权重(尚未使用)作为计数器.

  1. public class Reformatory
  2. {
  3. private int weight;
  4. public int weight(Person person)
  5. {
  6. int weight = person.getWeight();
  7. this.weight++;
  8. // return the weight of the person
  9. return weight;
  10. }
  11. public void Feed(Person person)
  12. {
  13. //that increases the weight of its parameter by one.
  14. person.setWeight(person.getWeight() + 1);
  15. }
  16. public int totalWeightsMeasured()
  17. {
  18. return weight;
  19. }
  20. }

猜你在找的Java相关文章