测验程序开发问题:如何为随机抽取的题目匹配对应正确答案
问题修复方案
1. 正确匹配题目与对应答案
你的核心问题是没有保存随机选中题目的索引,导致无法关联到对应的正确答案,同时原代码中btnCorrect.Text = Answers[];存在语法错误。修正步骤如下:
- 先生成并保存随机题目索引,而非直接赋值题目文本
- 用该索引获取对应的正确答案
- 生成错误选项时避免重复,且不能与正确答案重复
修正后的代码示例:
Random random = new Random(); // 生成随机题目索引(Next方法为左闭右开,正确范围是0到Questions.Count,无需减1) int selectedQuestionIndex = random.Next(Questions.Count); // 设置题目文本 lblQuestion.Text = Questions[selectedQuestionIndex]; // 获取对应正确答案 string correctAnswer = Answers[selectedQuestionIndex]; btnCorrect.Text = correctAnswer; // 生成不重复的错误选项 List<string> wrongAnswers = new List<string>(); while (wrongAnswers.Count < 3) { string candidate = Answers[random.Next(Answers.Count)]; // 排除正确答案和已选的错误选项 if (candidate != correctAnswer && !wrongAnswers.Contains(candidate)) { wrongAnswers.Add(candidate); } } // 给错误按钮赋值 btnIncorrect1.Text = wrongAnswers[0]; btnIncorrect2.Text = wrongAnswers[1]; btnIncorrect3.Text = wrongAnswers[2];
注意:原代码中random.Next(0, Questions.Count - 1)会漏掉最后一道题,正确写法是random.Next(Questions.Count),它会生成0到Questions.Count-1的随机数。
2. 解决lblQuestion.Text.Count()始终返回2的异常
你误解了Count()方法的作用:对于字符串lblQuestion.Text,Count()是统计字符个数,而非获取题目在列表中的索引。比如当前显示的题目文本是两个字符时,就会返回2。
如果需要获取当前题目的索引,不要通过文本反向查找(易因重复题目出错),直接复用之前生成的selectedQuestionIndex变量即可,示例:
// 保存索引后可直接用于后续逻辑 int currentQuestionIndex = selectedQuestionIndex; // 验证答案时用该索引对比 if (userInputAnswer == Answers[currentQuestionIndex]) { // 答对逻辑 }
内容的提问来源于stack exchange,提问作者JCunningham
相关产品推荐
相关产品推荐

