为什么我在 Java 中的枚举方法总是 return 最后一个值响应?

Why does my enum method in Java always return the last values response?

我目前正在尝试 Java 中的一个小东西:一个基于枚举的小型 diceroller。

我们的想法是能够调用一种方法,根据枚举的值,returns 掷骰子。

我的代码如下所示:

private static int result;

private static int randIntMinMax(int min, int max){
    Random rand = new Random();

    return (rand.nextInt((max - min) + 1) + min);
}

static {
    D2.result = randIntMinMax(1, 2);
    D3.result = randIntMinMax(1, 3);
    D4.result = randIntMinMax(1, 4);
    D6.result = randIntMinMax(1, 6);
    D8.result = randIntMinMax(1, 8);
    D10.result = randIntMinMax(1, 10);
    D12.result = randIntMinMax(1, 12);
    D20.result = randIntMinMax(1, 20);
    D100.result = randIntMinMax(1, 100);
}

public static int Roll(){

    return result;
}

public static int Roll(int amount){
    int added = 0;
    for(int i = 0; i < amount; i++){

        added += Roll();
    }

    return added;
}

当我做这样的事情时:

Dice DSix = Dice.D6;
int example = DSix.Roll();

我总是得到 D100 的 .Roll(); 的值,即行中的最后一个。

怎么会?

result 是与 class 关联的静态变量,因此始终具有最后分配的值。改用实例变量并使相应的方法成为实例方法。

public int getRollResult() {

    return result;
}