My problem is to find out how many times the weight()
method is being called from the main class. I should calculate it in the totalWeightsMeasured()
method.
The output of the code should be 0,2,6. (EDIT// I had earlier here 0,2,4 but the output should really be 0,2,6)
But I just don't have any idea how can you calculate it and I have tried to google and everything but I just don't know how to do it. (and you are not supposed to add any more instance variables)
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());
}
}
The trick is to use the existing instance variable weight, which is not used yet, as the counter.
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;
}
}
As pointed out by Satya, introduce a static
counter variable as follows:
public class Reformatory {
private static int weightMessurements = 0;
public int weight(Person person) {
// increment counter
weightMessurements++;
// messure weight
return person.getWeight();
}
public void feed(Person person) {
// increase weight
person.setWeight(person.getWeight() + 1);
}
public int totalWeightsMeasured() {
int result = weightMessurements;
// reset counter so that the output matches 0,2,4 instead of 0,2,6
weightMessurements = 0;
return result;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With