Home > Mobile >  How do I make a get method return a decreasing/increasing value for every time it is called?
How do I make a get method return a decreasing/increasing value for every time it is called?

Time:02-24

I have a unit(soldier) class which contains a getAttackBonus() method and a getResistBonus() method. These must return different values for every time a soldier either attacks or is attacked. To be specific, getResistBonus() can for example start at 8 but for every time the soldier is attacked, it will decrease by 2 until it reaches a certain value (for example 2 as a final resist bonus) where it will no longer decrease. How would I go about doing this?

Currently I am using in my method which does not work when I attempt to test it as a JUnit class, it keeps giving me 6 as the integer:

public int getResistBonus() {
    int resist = 8;
    while(resist != 2) {
        return resist -= 2;
    }
    return 2;
}

CodePudding user response:

You need to change a bit your code. First you need to define resist at instance level, not method level. Second it is better to use an if instead of a while because you are not making a loop, but only checking a single condition.

So the code can be something similar to that:

public class YourClass {
    // Define resist at instance level
    private int resist = 8;

    ....

    public int getResistBonus() {
      // Replace the while with an if
      if (resist > 2) {
         resist -= 2;
      }
      return resist;
    }
}
  • Related