You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Java测验程序开发求助:错题重答与分数计算修正问题

Java测验程序解决方案:功能实现与Bug修复

Got it, let's work through this Java quiz program step by step—we'll tackle all your requirements and fix that wonky scoring bug once and for all.

一、核心需求拆解

First, let's clarify exactly what we need to build:

  • 错题重复作答:用户答错题目时,重复展示该题直到答对,并且答错后立即显示正确答案作为提示
  • 精准分数计算:每道题仅首次答对时加分,后续答错后再答对不加分;总分严格锁定为150分,杜绝重复累加导致的分数溢出
  • 答错次数触发回溯:当累计答错次数达到5次时,回到之前答错2次的题目重新作答
  • 题量规模:测验包含28道题目

二、现有代码核心Bug分析与修复

That "178 score after 5 wrong answers" issue almost certainly comes from accidental repeated scoring—like adding points every time a user answers correctly, even if they already got the right answer before, or scoring logic firing in the wrong part of the loop.

Here's how we fix it:

  1. Track answered questions: Add a flag to each question to mark if it's been correctly answered already
  2. Isolate scoring logic: Only run the score increment code when a question is answered correctly for the first time
  3. Track wrong attempts globally and per question: Use these counts to trigger the backtracking logic

三、完整实现示例

1. 题目实体类(Question)

First, we'll define a Question class to store all necessary data for each quiz item:

public class Question {
    private String questionText;
    private String correctAnswer;
    private int points;
    private boolean isAnsweredCorrectly;
    private int wrongAttempts;

    public Question(String questionText, String correctAnswer, int points) {
        this.questionText = questionText;
        this.correctAnswer = correctAnswer;
        this.points = points;
        this.isAnsweredCorrectly = false;
        this.wrongAttempts = 0;
    }

    // Getters and Setters
    public String getQuestionText() { return questionText; }
    public String getCorrectAnswer() { return correctAnswer; }
    public int getPoints() { return points; }
    public boolean isAnsweredCorrectly() { return isAnsweredCorrectly; }
    public void setAnsweredCorrectly(boolean answeredCorrectly) { isAnsweredCorrectly = answeredCorrectly; }
    public int getWrongAttempts() { return wrongAttempts; }
    public void incrementWrongAttempts() { wrongAttempts++; }
}

2. 测验主逻辑(QuizProgram)

Now the core quiz logic, with all your requirements implemented:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class QuizProgram {
    private List<Question> questions;
    private int totalScore;
    private int totalWrongAttempts;
    private Scanner scanner;

    public QuizProgram() {
        questions = new ArrayList<>();
        totalScore = 0;
        totalWrongAttempts = 0;
        scanner = new Scanner(System.in);
        init28Questions(); // Initialize all 28 questions
    }

    private void init28Questions() {
        // Ensure total points add up to 150: 26 questions worth 5 points (130 total) + 2 questions worth 10 points (20 total)
        for (int i = 1; i <= 26; i++) {
            questions.add(new Question(
                "Question " + i + ": What is the result of 3 * 5?", 
                "15", 
                5
            ));
        }
        questions.add(new Question(
            "Question 27: Which Java keyword is used to declare a constant?", 
            "final", 
            10
        ));
        questions.add(new Question(
            "Question 28: What does JVM stand for?", 
            "Java Virtual Machine", 
            10
        ));
    }

    public void startQuiz() {
        int currentQuestionIndex = 0;
        while (currentQuestionIndex < questions.size()) {
            Question currentQ = questions.get(currentQuestionIndex);
            
            // Skip questions already answered correctly
            if (currentQ.isAnsweredCorrectly()) {
                currentQuestionIndex++;
                continue;
            }

            // Display the question
            System.out.println("\n" + currentQ.getQuestionText());
            System.out.print("Your answer: ");
            String userAnswer = scanner.nextLine().trim();

            // Check user's answer
            if (userAnswer.equalsIgnoreCase(currentQ.getCorrectAnswer())) {
                // Only add points if this is the first correct answer
                if (!currentQ.isAnsweredCorrectly()) {
                    totalScore += currentQ.getPoints();
                    currentQ.setAnsweredCorrectly(true);
                    System.out.println("Correct! Current score: " + totalScore);
                } else {
                    System.out.println("Correct! You already nailed this one. Score stays at: " + totalScore);
                }
                currentQuestionIndex++; // Move to next question
            } else {
                // Handle wrong answer
                currentQ.incrementWrongAttempts();
                totalWrongAttempts++;
                System.out.println("Oops, wrong answer! The correct answer is: " + currentQ.getCorrectAnswer());
                System.out.println("Total wrong attempts so far: " + totalWrongAttempts);

                // Trigger backtracking if total wrong hits 5
                if (totalWrongAttempts == 5) {
                    System.out.println("\nYou've hit 5 wrong attempts! Let's go back to the question you messed up twice.");
                    // Find the first question with 2 wrong attempts that's not yet answered correctly
                    for (int i = 0; i < questions.size(); i++) {
                        Question q = questions.get(i);
                        if (q.getWrongAttempts() == 2 && !q.isAnsweredCorrectly()) {
                            currentQuestionIndex = i;
                            break;
                        }
                    }
                    totalWrongAttempts = 0; // Reset counter after backtracking
                }
                // Stay on current question to let user try again
            }
        }

        // Quiz completion
        System.out.println("\n🎉 Quiz finished! Your final score: " + totalScore + "/150");
        scanner.close();
    }

    public static void main(String[] args) {
        QuizProgram quiz = new QuizProgram();
        quiz.startQuiz();
    }
}

3. Key Logic Breakdown

  • 错题重复作答: When a user answers wrong, we don't increment currentQuestionIndex, so the loop will redisplay the same question until they get it right
  • Accurate Scoring: The score only increments when isAnsweredCorrectly is false—so no duplicate points for re-correcting a question
  • Backtracking: When total wrong hits 5, we loop through questions to find the first one with 2 wrong attempts and jump back to it
  • Total Score Control: We initialized questions to add up exactly to 150 points, so a perfect score will always be 150

四、Testing Tips

  • Test repeated wrong answers: Score shouldn't change until the first correct response
  • Trigger backtracking: After 5 wrong answers, you should jump back to the question you messed up twice
  • Perfect score test: Answer all correctly, final score should be exactly 150

内容的提问来源于stack exchange,提问作者Vince Jack Ludovice

火山引擎 最新活动