如何声明具有最小值和最大值的 Int?

How to declare an Int that has a minimum and a maximum?

标题说明了一切,在我的 Slick2D 状态下,我正在跟踪 MouseX 和 MouseY 坐标,我希望 X 介于 8 < MouseX < 944 和 Y 之间 8 < MouseY < 573。这是相关的代码位(如果需要...):

int xpos = Mouse.getX();
int ypos = Mouse.getY();

您必须使用 Setter 来实现:

public void setXPos (int x){
    if (x < 8){
        this.xPos = 8;
    } else if (x > 944){
        this.xPos = 944;
    } else {
        this.xPos = x;
    }
}

intInteger 都无法将值绑定到范围。您需要自己编写此逻辑。

您应该如何以及在何处实现逻辑取决于您要实现的目标。

这是一个解决方案:

int xpos = Math.max(Math.min(Mouse.getX(), 944), 8);
int ypos = Math.max(Math.min(Mouse.getY(), 573), 8);