0

I'm making a "Who Wants to be a Millionaire" type of quiz game for a University assignment but I can't find a way to randomly assign the 4 answer strings in my string array to my 4 answer JButtons without duplicates. I've tried a few solutions that I found online and the best I managed to do was randomly set the text but with a chance for a duplicate (a fairly high chance of course as there's only 4 strings).

Can anyone help?

 if (currentGKQNum <=9){
                currentQuestion = Game.getGKQuestion(currentGKQNum); //gets a question object at the index specified by currentGKQNum
                questionLabel.setText(currentQuestion.getQuestion()); //gets the actual question string from the question object and assigns it to question label
                currentGKQNum += 1;
            }

            else{
                questionLabel.setText("End of general knowledge questions");
            }

            String[] answers = new String[] {currentQuestion.getAnswer1(),currentQuestion.getAnswer2(),currentQuestion.getAnswer3(),currentQuestion.getCorrectAnswer()};

            answer1Button.setText(//need random string from answers[] here)
            answer2Button.setText(//need random string from answers[] here)
            answer3Button.setText(//need random string from answers[] here)
            answer4Button.setText(//need random string from answers[] here)
SpooK
  • 1
  • Keyword here is "permutation" - that's your "random assignment without duplicates". Shuffle your questions, then assign them to your buttons sequentially. There would be no duplicates. – Sergey Kalinichenko Mar 15 '18 at 08:57

1 Answers1

1

Convert your array to list and shuffle the list.

String[] str = new String[] { "one", "two", "three" };
List<String> list = Arrays.asList(str);
Collections.shuffle(list);

Then get the texts from the list.

MatheM
  • 801
  • 7
  • 17