尝试避免连续相同的随机数时,引用相等性测试失败

时间:2018-08-06 17:03:40

标签: java javafx random equality

我正在学习Javafx。我出于练习目的而编写测验应用程序。

现在,我正在研究有关随机问题顺序的功能。我使用 javafx.scene.control.Button 通过 Random 类实现这一点。

我试图避免连续的随机数,所以我使用if语句来测试两个引用的相等性。 问题是,有时它不起作用,我仍然得到相同的连续随机数,结果似乎不应该存在。

这是我的代码段:

buttonRandom.setOnAction(new EventHandler<ActionEvent>() {
        Question oldQuestion = currentQuestion;
        int randomIndexOfList;
        Random randomGenerator = new Random();
        @Override
        public void handle(ActionEvent event) {
            if (questionLibrary.getQuestionsList().size() > 1) {
                randomIndexOfList = randomGenerator.nextInt(questionLibrary.getQuestionsList().size());
                currentQuestion = questionLibrary.getQuestionsList().get(randomIndexOfList);
                if (currentQuestion == oldQuestion) {
                    buttonRandom.fire();
                }
                else {
                    System.out.println(currentQuestion.getIndex());
                    updateQuestionDisplay();
                }
            }
            else
                new Alert(Alert.AlertType.ERROR, "There are less than 2 questions in Library.").showAndWait();
        }
    });

这是它的一些测试结果:

70
93
93

20
65
174
51
70
93
65
119
105
47
47

51

我还尝试使用 equals ()方法(在 Question 类中很好地实现)测试相等性,或测试 index 字段在< em>问题,但问题仍然存在。使用do-while循环进行的测试也没有帮助...

我正在将IntelliJ IDEA与Java sdk 1.8 .0_181一起使用。

非常感谢您分享的所有光线,谢谢。

1 个答案:

答案 0 :(得分:0)

我自己弄清楚了。 一个非常愚蠢的错误。 我错误地将Question oldQuestion = currentQuestion;声明从handle(ActionEvent event)方法中删除,使oldquestion在实例化EventHandler之后再也没有被重新分配。

更正:

        int randomIndexOfList;
        Random randomGenerator = new Random();
        @Override
        public void handle(ActionEvent event) {
            Question oldQuestion = currentQuestion;
            if (questionLibrary.getQuestionsList().size() > 1) {

我应该把头撞成驴子。