为了账号安全,请及时绑定邮箱和手机立即绑定

随机枚举返回空

随机枚举返回空

达令说 2021-06-07 17:24:39
您好,我正在尝试获取随机 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 回答

?
慕码人2483693

TA贡献1860条经验 获得超9个赞

你的问题似乎在这里


private void Lottery(){

    this.singOne = lotteryMachine.randomSing();

    this.singTwo = lotteryMachine.randomSing();

    this.singThree = lotteryMachine.randomSing();

}

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


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();

}


查看完整回答
反对 回复 2021-06-10
  • 1 回答
  • 0 关注
  • 157 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信