如何在另一个变量超过某个值时经常向变量添加增量?

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

我正在为自己编写一个程序,用于学习 java。这是某种实验。它具有 class 元素,例如玩家、动作、怪物、物品、游戏玩法。在我的 class 播放器中,我添加了一个名为 lvlUp 的构造函数,参数为 exp。我的问题是,当我想在玩家达到 100 exp、200 exp、300 exp 等时增加他的等级时,我必须写什么。当他有 100 exp 时,他会升一级,当他有 200 exp 时,他得到 2 级提升,等等。顺便说一句,exp 是随机的,所以我也想打印出剩余的 exp。例如,他杀死一只怪物并获得 245 exp,这应该是 2 级提升和 45 exp。这是我的自动取款机代码:

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

猜猜这会完成工作

// your class code
int exp = 0;
int lvl = 0;
// ...

public int lvlUp(int exp){  // increase the experience by exp and update the level
    this.exp += exp;
    lvl = exp / 100;  // integer division
    System.out.println("Levels: " + lvl + ", experience left: " + exp % 100);
    return lvl;
}

您需要像 lvlBar 这样的全局变量。这将作为玩家的等级计数器来查看他们升级所需的经验。

首先,你必须弄清楚玩家应该升级多少级。要计算它,请除以 100。

int levels = exp / 100;

由于这是整数运算,它会为您截断。 (因此在您的 exp = 245 示例中,级别将为 2。

接下来,使用该值计算出用户还剩下多少体验。

exp = exp - (levels * 100);

最后,添加新关卡。

this.lvl += levels;