Java实现数组无重复随机取元素:getNextQuestion方法如何编写?
getNextQuestion() in Java GUI Question Bank Got it, let's work through this problem. You need a method that pulls a random, never-before-asked question each time your JButton is clicked—no repeats until all questions are exhausted, right? Here are two solid approaches to implement this, depending on your needs:
Approach 1: Track Remaining Question Indices
This method keeps a list of indices for questions that haven't been asked yet. Each time you fetch a question, you randomly pick an index from the list, remove it (so it can't be picked again), and return the corresponding question. When all indices are used up, you can reset the list to start over.
Full Code Implementation
import java.util.ArrayList; import java.util.List; import java.util.Random; public class QuestionBank { String[] questions; List<Integer> remainingQuestionIndices; Random randomGenerator; public QuestionBank() { questions = new String[10]; // Initialize your question array questions[0] = "Which three words describe you best?"; questions[1] = "Which is your best feature?"; questions[2] = "Which common saying or phrase describes you?"; questions[3] = "What’s the best thing that’s happened to you this week?"; questions[4] = "Who was your role model when you were a child?"; questions[5] = "Who was your favorite teacher and why?"; questions[6] = "What was your favorite subject at school?"; questions[7] = "What did you want to be when you grew up?"; questions[8] = "If you could have one wish come true what would it be?"; questions[9] = "Which would you prefer — three wishes over five years or one wish right now?"; // Set up list to track unused question indices remainingQuestionIndices = new ArrayList<>(); for (int i = 0; i < questions.length; i++) { remainingQuestionIndices.add(i); } randomGenerator = new Random(); } public String getNextQuestion() { // Handle case where all questions have been asked if (remainingQuestionIndices.isEmpty()) { // Optional: Reset the question bank to start over resetQuestionBank(); // Alternative: Return null to signal no more questions // return null; } // Pick a random index from the remaining list int randomListIndex = randomGenerator.nextInt(remainingQuestionIndices.size()); int questionIndex = remainingQuestionIndices.remove(randomListIndex); return questions[questionIndex]; } // Helper method to reset the question bank for repeated use public void resetQuestionBank() { remainingQuestionIndices.clear(); for (int i = 0; i < questions.length; i++) { remainingQuestionIndices.add(i); } } }
Key Notes:
- The
remainingQuestionIndiceslist ensures no question is repeated until the list is empty. - We initialize
Randomonce instead of creating a new instance every time—this is more efficient and avoids potential seed-related issues. - The
resetQuestionBank()method lets you loop through questions again once all have been used.
Approach 2: Shuffle and Traverse
This approach shuffles the entire list of questions once, then returns them in the shuffled order until all are used. When the end is reached, you re-shuffle and start over.
Full Code Implementation
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class QuestionBank { String[] questions; List<String> shuffledQuestions; int currentQuestionPosition; public QuestionBank() { questions = new String[10]; // Initialize your question array questions[0] = "Which three words describe you best?"; questions[1] = "Which is your best feature?"; questions[2] = "Which common saying or phrase describes you?"; questions[3] = "What’s the best thing that’s happened to you this week?"; questions[4] = "Who was your role model when you were a child?"; questions[5] = "Who was your favorite teacher and why?"; questions[6] = "What was your favorite subject at school?"; questions[7] = "What did you want to be when you grew up?"; questions[8] = "If you could have one wish come true what would it be?"; questions[9] = "Which would you prefer — three wishes over five years or one wish right now?"; // Convert array to list and shuffle shuffledQuestions = new ArrayList<>(Arrays.asList(questions)); shuffleQuestionList(); currentQuestionPosition = 0; } public String getNextQuestion() { // Handle case where all questions have been asked if (currentQuestionPosition >= shuffledQuestions.size()) { // Re-shuffle and reset position shuffleQuestionList(); currentQuestionPosition = 0; // Alternative: Return null to signal no more questions // return null; } return shuffledQuestions.get(currentQuestionPosition++); } // Helper method to shuffle the question list private void shuffleQuestionList() { Collections.shuffle(shuffledQuestions); } }
Key Notes:
- Uses
Collections.shuffle()to randomize the question order in one go—great if you want a fixed random sequence per full cycle of questions. currentQuestionPositiontracks where you are in the shuffled list, so you don't repeat questions until the cycle ends.
Which Approach Should You Choose?
- Use Approach 1 if you want truly random questions every time (no fixed sequence even mid-cycle).
- Use Approach 2 if you prefer a consistent random order for each full set of questions (easier to track progress through all questions).
Both methods integrate seamlessly with your JButton click listener—just call getNextQuestion() when the button is pressed and display the result!
内容的提问来源于stack exchange,提问作者Yacoub Mahamat

