How to add incrementation to a variable as often as another one surpasses a certain value?

Larry :

I am coding a program for myself, for learning java. It is some kind of experiment. It has classes like player, actions, monsters, items, gameplay. In my class player, i added a constructor which i called lvlUp with the parameter exp. My question is, what do I have to write when I want to increment the lvl of a player when he reaches 100 exp, 200 exp, 300 exp etc. When he has 100 exp, he gets one level up, when he has 200 exp, he gets 2 lvl ups, etc. . Btw, the exp is random, so I would like to print out the remaining exp as well. For example, he kills one monster and earns 245 exp, that should be 2 lvl ups and 45 exp. this is my code atm:

public int lvlUp(int exp) {
    if (exp < 100) {
        System.out.println("LvL: " + this.lvl + " You have " + exp + " experience!");
    } else if (exp == 100) {
        System.out.println("Level up !!!");
        exp = 0;
        this.lvl++;
    } else if (exp > 100) {
        System.out.println("Level up !!!");
        exp = exp - 100;
        this.lvl++;
        System.out.println("LvL: " + this.lvl + " You have " + exp + " experience!");
    }
    return this.lvl++;
Bill the Lizard :

First, you have to figure out how many level ups the player should get. To calculate that, divide by 100.

int levels = exp / 100;

Since that's integer arithmetic, it will truncate for you. (So in your example of exp = 245, level will be 2.

Next, use that value to figure out how much experience the user has left over.

exp = exp - (levels * 100);

Finally, add the new levels.

this.lvl += levels;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=128378&siteId=1