Java 随机枚举返回null

Java 随机枚举返回null,java,random,enums,Java,Random,Enums,您好,我正在尝试获取随机枚举,但它返回null,有人可以帮助我,我的代码中有什么错误?我试图独自修理它,但我放弃了 public class LotteryMachine { protected enum Sings { ONE, TWO, THREE } private static final List<Sings> SINGS_LIST = Collections.unmodifiableList(Arrays.

您好,我正在尝试获取随机枚举,但它返回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);
    }
}
公共类彩票机{
受保护枚举{
一
二
三
}
私有静态最终列表SINGS_List=Collections.unmodifiableList(Arrays.asList(SINGS.values());
私有静态final int SIZE=SINGS_LIST.SIZE();
私有静态最终随机=新随机();
唱歌随机化{
return SINGS_LIST.get(RANDOM.nextInt(SIZE));
}
}
公开课游戏{
私有LotteryMachine LotteryMachine=新的LotteryMachine();
私人彩票机;
私人彩票机。唱两首歌;
私人彩票机。唱三;
私人彩票{
this.singOne=lotteryMachine.randomSing();
this.singtow2=lotteryMachine.randomSing();
this.singtree=lotteryMachine.randomSing();
}
公共彩票{
系统输出打印(单选一+单选二+单选三);
}
}

您的问题似乎就在这里

private void Lottery(){
    this.singOne = lotteryMachine.randomSing();
    this.singTwo = lotteryMachine.randomSing();
    this.singThree = lotteryMachine.randomSing();
}
这不是一个构造函数;相反,它是一个名为
lotking()
的私有方法,
Game
类不使用它。由于从未调用该方法,因此所有
singX
字段都未初始化(即null)。在您将初始化逻辑从所述方法移动到如下字段声明之后,应该可以正常工作

private LotteryMachine.Sings singOne = lotteryMachine.randomSing();
private LotteryMachine.Sings singTwo = lotteryMachine.randomSing();
private LotteryMachine.Sings singThree = lotteryMachine.randomSing();
或者声明
游戏
类的构造函数,如下所示:

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

我试过了,我没有空。你打电话给我了吗viewtocket()之前的代码>?您能显示您呼叫的代码吗?请给出您如何使用这些代码this@azro它是如何强制的?彩票()只是一个方法,而不是构造函数。