如何使 get 方法 return 每次调用时都具有 decreasing/increasing 值?

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

我有一个单位(士兵)class,其中包含一个 getAttackBonus() 方法和一个 getResistBonus() 方法。每次士兵攻击或被攻击时,这些值必须 return 不同。 具体来说,getResistBonus() 例如可以从 8 开始,但每次士兵受到攻击时,它都会减少 2,直到达到某个值(例如 2 作为最终抵抗奖励),它不再减少。我该怎么做?

目前我正在使用我的方法,当我尝试将它作为 JUnit 进行测试时它不起作用 class,它一直给我 6 作为整数:

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

您需要稍微更改一下代码。 首先,您需要在实例级别而不是方法级别定义抵抗。 其次,最好使用 if 而不是 while,因为您不是在进行循环,而只是检查一个条件。

所以代码可以类似于:

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;
    }
}