随机枚举返回null

时间:2018-07-24 16:49:00

标签: java random enums

您好,我尝试获取随机ENUM,但它返回null,有人可以帮助我我的代码有什么问题吗?我试图独自修理它,但我放弃了。

public class LotteryMachine {
    protected enum Sings {
        ONE,
        TWO,
        THREE
}

    private static final List<Sings> SINGS_LIST = Collections.unmodifiableList(Arrays.asList(Sings.values()));
    private static final int SIZE = SINGS_LIST.size();
    private static final Random RANDOM = new Random();

    Sings randomSing() {
        return SINGS_LIST.get(RANDOM.nextInt(SIZE));

    }
}


public class Game {

    private LotteryMachine lotteryMachine = new LotteryMachine();

    private LotteryMachine.Sings singOne;
    private LotteryMachine.Sings singTwo;
    private LotteryMachine.Sings singThree;

    private void Lottery(){
        this.singOne = lotteryMachine.randomSing();
        this.singTwo = lotteryMachine.randomSing();
        this.singThree = lotteryMachine.randomSing();
    }

    public void viewLottery(){
        System.out.print(singOne + " " + singTwo + " " + singThree);
    }
}

1 个答案:

答案 0 :(得分:1)

您的问题似乎在这里

private void Lottery(){
    this.singOne = lotteryMachine.randomSing();
    this.singTwo = lotteryMachine.randomSing();
    this.singThree = lotteryMachine.randomSing();
}

这不是构造函数;相反,它是一个名为Lottery()的私有方法,未被Game类使用。由于从未调用过该方法,因此所有singX字段都未初始化(即为null)。在将初始化逻辑从所述方法移动到像这样的字段声明之后,事情应该可以工作

private LotteryMachine.Sings singOne = lotteryMachine.randomSing();
private LotteryMachine.Sings singTwo = lotteryMachine.randomSing();
private LotteryMachine.Sings singThree = lotteryMachine.randomSing();

或另外声明Game类的构造函数,如下所示:

public Game() {
    this.singOne = lotteryMachine.randomSing();
    this.singTwo = lotteryMachine.randomSing();
    this.singThree = lotteryMachine.randomSing();
}