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

时间:2015-05-09 19:44:55

标签: java enums

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

这个想法是能够调用一个方法,根据枚举的值,返回一个骰子卷。

我的代码如下所示:

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();的值,这是行中的最后一个。

怎么回事?

1 个答案:

答案 0 :(得分:4)

result是一个与类关联的静态变量,因此始终具有最后指定的值。使用实例变量代替并生成相应的方法实例方法。

public int getRollResult() {

    return result;
}