我的问题是找出从主类调用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.jb51.cc/java/437234.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。