You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java安卓答题应用随机出题重复问题求助(附代码)

Fixing Duplicate Questions & Implementing One-Time Quiz Flow

Hey there! Let's sort out your duplicate question problem and get that "each question once, end after 10" flow working. Your current code has two key issues:

  • You're using Random.nextInt() which can pick the same index repeatedly (hence duplicate questions)
  • Your Collections.shuffle(list) is acting on an empty list—so it's doing nothing at all

Here's the revised code with clear improvements:

public class MainActivity extends AppCompatActivity {
    Button answer1, answer2, answer3;
    TextView Score, Question;
    private Questions mQuestions = new Questions();
    private String mAnswer;
    private int mScore = 0;
    private int mQuestionsLength;
    // Track our position in the shuffled question list
    private int currentQuestionPos = 0;
    // List to hold shuffled question indices (no repeats guaranteed)
    private List<Integer> shuffledQuestionIndices;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        answer1 = findViewById(R.id.answer1);
        answer2 = findViewById(R.id.answer2);
        answer3 = findViewById(R.id.answer3);
        Score = findViewById(R.id.Score);
        Question = findViewById(R.id.Question);

        mQuestionsLength = mQuestions.mQuestions.length;
        Score.setText("Score: " + mScore);

        // Set up our shuffled index list
        shuffledQuestionIndices = new ArrayList<>();
        for (int i = 0; i < mQuestionsLength; i++) {
            shuffledQuestionIndices.add(i);
        }
        Collections.shuffle(shuffledQuestionIndices);

        // Load the first question
        updateQuestion();

        answer1.setOnClickListener(view -> handleAnswer(answer1.getText().toString()));
        answer2.setOnClickListener(view -> handleAnswer(answer2.getText().toString()));
        answer3.setOnClickListener(view -> handleAnswer(answer3.getText().toString()));
    }

    // Reusable answer handling logic to avoid code duplication
    private void handleAnswer(String selectedAnswer) {
        if (selectedAnswer.equals(mAnswer)) {
            mScore++;
            Score.setText("Score: " + mScore);
        } else {
            gameOver();
            return;
        }

        currentQuestionPos++;
        // Check if we've finished all questions
        if (currentQuestionPos >= mQuestionsLength) {
            quizCompleted();
        } else {
            updateQuestion();
        }
    }

    private void updateQuestion() {
        // Get the pre-shuffled index for the current question
        int questionIndex = shuffledQuestionIndices.get(currentQuestionPos);
        Question.setText(mQuestions.getQuestion(questionIndex));
        answer1.setText(mQuestions.getChoice1(questionIndex));
        answer2.setText(mQuestions.getChoice2(questionIndex));
        answer3.setText(mQuestions.getChoice3(questionIndex));
        mAnswer = mQuestions.getCorrectAnswer(questionIndex);
    }

    private void gameOver() {
        // Add your game over logic here (e.g., show a dialog, reset the quiz)
        Toast.makeText(this, "Game Over!", Toast.LENGTH_SHORT).show();
    }

    private void quizCompleted() {
        // Logic for when all 10 questions are done
        Toast.makeText(this, "Quiz Done! Final Score: " + mScore, Toast.LENGTH_LONG).show();
        // Optional: Disable buttons to prevent further input
        answer1.setEnabled(false);
        answer2.setEnabled(false);
        answer3.setEnabled(false);
    }
}

Key Fixes & Improvements:

  1. Shuffled Index List: We create a list of all question indices, shuffle it once, then iterate through it in order—this ensures every question is shown exactly once.
  2. Reusable Answer Handler: Moved answer checking logic into a single method to avoid repeating code across button listeners.
  3. Fixed String Comparison: Replaced == with equals() for text checks—== compares object references, not actual text content, which would have caused incorrect scoring.
  4. Quiz Completion Check: After each correct answer, we check if we've gone through all questions. If yes, trigger the completion logic.
  5. Cleaned Up Unused Code: Removed the unused Random instance since we no longer need it.

Extra Tips:

  • If you want to let users restart the quiz, add a restart button that resets currentQuestionPos to 0, reshuffles the index list, re-enables buttons, and resets the score.
  • Double-check that your Questions class methods (getQuestion, getChoice1, etc.) correctly return values for each index.

内容的提问来源于stack exchange,提问作者solid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:36:10