Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading