lundi 6 août 2018

Reference equality test failed when trying to avoid consecutive same random number

I am learning Javafx. I'm writing an quiz application for practice purpose.

Now I'm working on a feature about random question order. I use javafx.scene.control.Button to implement that, with Random class.

I'm trying to avoid consecutive random number, so I use an if-statement to test equality of two reference. The problem is that some times it doesn't work, I still got same consecutive random numbers and results which seems should not be there.

here is my code snippet:

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

And here are some test results of it: 70 93 93 20 65 174 51 70 93 65 119 105 47 47 51

I also tried to test equality with equals() method(which is well implemented in Question class) or test index fields in Question directly, but problem stand still. And a test using a do-while loop had no help too...

I 'm using IntelliJ IDEA with java sdk 1.8 .0_181.

Most appreciated for any light you can share, Thanks.




Aucun commentaire:

Enregistrer un commentaire