我在解决这个问题上遇到了麻烦。我有一个while语句,该表达式应在每个循环上求值。我觉得我在想这个错误。

我想做的是遍历表达式experience >= experienceCap直到它为假。 experienceCap在每个循环上都已正确设置,但是while表达式值永远不会改变,即使值实际上在每个循环上确实会发生变化。

public void refreshExperience() {
    int experience = getExperience(); //10
    int experienceCap = getExperienceCap(); //100

    while (experience >= experienceCap) {
            newExperienceCap();
            refreshExperience();
    }

}


这将导致一些日志输出,例如:

experience: 10
experienceCap: 100
experience: 10
experienceCap: 450
experience: 10
experienceCap: 1120
experience: 10
experienceCap: 2337


不可避免的崩溃。
我非常感谢您的任何投入,谢谢!

最佳答案

循环值未更新,因此令人困惑的是,在您的输出中它显示experienceCap增加。在没有看到所有代码的情况下,我只能猜测您记录的值不是在refreshExperiece中声明的值。

public class Test {

    int experience = 10;
    int experienceCap = 100;

    public void refreshExperience() {
        while (experience <= experienceCap) {
            experience = getExperience();
            experienceCap = getExperienceCap();
        }
    }


上面的代码显示将experience和experienceCap分别初始化为10和100。在循环内部,分别使用getExperience和getExperienceCap的返回值更新这些值。您如何更新体验和ExperienceCap取决于您,但这是一个简单的示例:

private int getExperience() {
    return experience + 5;
}

private int getExperienceCap() {
    return experienceCap - 10;
}

09-27 11:51