Roberto Roberto - 1 year ago 59
Java Question

Random answer possibilities

I made a fairly solid quiz game in Android for my class where 10 random questions are picked from an array. The way it's working right now is that the user enters the answer in an EditText field. I'm also happy that I was able to figure out how not to get duplicate questions using a simple shuffle algorithm so every question thrown at the user is unique (I'm actually pretty proud of that).

Ideally wanted to make the game to be multiple choice but I ran out of time and I submitted it as above. But I've been thinking about ways to make the game betters and user friendly and I think the EditText choice is not ideal IMO. So I've been thinking about rewriting it like this:

  1. A random question is selected;

  2. The question will display 4 random answer choices, and one of them will be the right answer;

  3. I will use RadioButtons and RadioGroup for the answer selection;

  4. The tricky part: I want the answer choices to be displayed and sorted randomly, for example:

    • questions x gets selected and answer choice will be displayed in a random order a, b, c, rightAnswer;

    • then question y gets selected and answer choices will be b, rightAnswer, c, a

    • etc...

So I was wondering if someone could point me in the right direction on how to achieve this. I'm not asking for full code, just places where I could read more about it and help me figure it out. All I seem to find in SO are ways to get random questions.

Thanks in advance!

Answer Source

create an array to hold your answers. and then choose a random number from 0-[array.length] and set that index in the array to the correct answer. ie:

int[] answers = new int[4];
answers[0] = getRandomAnswer();
answers[1] = getRandomAnswer();
answers[2] = getRandomAnswer();
answers[3] = getRandomAnswer();

int correctIndex = Random.nextInt(0,4); // Maybe off by 1? I didn't compile
answers[correctIndex] = correctAnswer;

Now you have an array that contains 3 random answers and 1 correct answer. You'll want to either make sure that getRandomAnswer() method won't return the correct answer to you, or check your array at this point for multiple instances of the correct answer and if they exist remove all but one.

you could populate a RadioGroup with the answers in your array and you know if the user is correct by checking against the correctIndex variable when they select one of the radio buttons in the group.