lundi 23 janvier 2017

Android: How to generate different random numbers

I'm new to Android programming and I'm making a math questions app that generates random numbers a and b then do a divided by b and add it to an ArrayList called answers. After that, the numbers are put into buttons and the user chooses the right answer.

The problem is that the wrong answers are, sometimes, generating the same number. For example:

10 / 2 = 5.

5 is added to the array list, then later to one of the buttons. Then again on the wrong answers, I have for example 2, 4, 4. Should be 2, 4, anotherNumber.

I've searched thoroughly here as demanded before asking questions and found advice to use HashSet, List with Shuffle and some other codes but I couldn't implement them in my code. There was always something missing/wrong.

ArrayList<Float> answers = new ArrayList<>();

    public void generateDivideQuestion(){

    // GENERATE QUESTIONS
    // Create random numbers between 1 and 19.
    Random rand = new Random();
    float a = rand.nextInt(20);
    float b = rand.nextInt(20);
    DecimalFormat df = new DecimalFormat("###.#");

    // Update the textview that shows the sums
    txtSum.setText(Integer.toString((int) a) + " / " + Integer.toString((int) b));

    //Answers
    locationOfCorrectAnswer = rand.nextInt(4);  //generate a random number which is 0,1,2 or 3
    float incorrectAnswer;    

    // Erase the content of our answers array list each time we generate a new question.
    answers.clear();

    //Loop to find the correct answer place
    for (int i = 0; i < 4; i++) {
        if (i == locationOfCorrectAnswer) {
            answers.add(a / b);             //generate correct answer in the array list
        } else {

            incorrectAnswer = Float.valueOf(rand.nextInt(20));

            // If the incorrect answer is equal to the correct answer, generate another one
            while (incorrectAnswer == a / b) {
                incorrectAnswer = Integer.valueOf(rand.nextInt(20));
            }

            answers.add(incorrectAnswer);    //generate incorrect answer in the array list

        } // END ELSE
    } // END FOR


    // Add the answers in the text field of the buttons
    btn1.setText(df.format(answers.get(0)));
    btn2.setText(df.format(answers.get(1)));
    btn3.setText(df.format(answers.get(2)));
    btn4.setText(df.format(answers.get(3)));
}




Aucun commentaire:

Enregistrer un commentaire