在 Java 中每秒将 int 从 10 减少到 0

Decreasing an int from 10 to 0 every second in Java

我定义一个

int x = 10;

现在我希望 x 每秒减少 直到它的 0:

if (Obstacle.activeItem == true) {
        game.font.draw(game.batch, "Item active for: " + x, 100, 680);
}

我该怎么做?

我见过有人用 Class Timer 做类似的事情,但我不知道这种情况应该是什么样子。

我试过了

int x = 10;
ScheduledExecutorService execService = Executors.newScheduledThreadPool(1);

然后

if (Obstacle.activeItem == true) {
            game.font.draw(game.batch, "Item active for: " + x, 100, 680);
}
execService.scheduleAtFixedRate(new Runnable() {
    public void run() {
        x--;
    }
}, 0L, 10L, TimeUnit.SECONDS);

但这并不如我所愿。

这是一个示例,说明如何使用执行器实现计时器类型的功能

public class Main {
    static int x = 10;

    public static void main(String[] args) {
        ScheduledExecutorService execService = Executors.newScheduledThreadPool(1);
        execService.scheduleAtFixedRate(() -> {
            System.out.println(x);
            x--;
            if (x == 0)
                execService.shutdownNow();
        }, 1L, 1L, TimeUnit.SECONDS); //initial delay, period, time unit
    }
}

强烈建议您阅读执行器。将此视为提示并相应地在您的用例中实施它。

你用 libGdx 标记了你的问题,所以我认为你在使用 libgdx。 为什么不使用 update(float delta) 方法来减少计时器而不是创建额外的 ExecutorService?

private float timer = 10;
@Override
public void render(float delta) {

    timer -= delta;

    if (Obstacle.activeItem == true) {
        font.draw(batch, "Item active for: " + (int)timer, 100, 680);
    }
}

如果那是 libGdx 我有一些工作用的意大利面条代码给你:

int reducedInt = 10;
bool isReduce = false;
float timer = 1f;

在渲染中

timer -= delta;


if(timer<=0){

isReduce = true;
timer = 1;

}
if(isReduce){

reducedInt--;
isReduce = false;

}

这是经典的 LibGDX sphagetti 计时器代码。由于您已将其标记为 LibGDX.