首页 > 解决方案 > 我如何在数组中提供 AD 作为正确答案,而不是 0-3?

问题描述

我刚刚开始使用 C# 进行编程,并且在某个特定部分上非常挣扎。我整理了一个多项选择测验,并在一个数组中列出了参数。我遇到的麻烦是如何生成字母 AD 作为正确答案,而不是 0、1、2、3。任何人都可以帮忙吗?我觉得这很简单,但我就是想不通。将不胜感激任何帮助,谢谢!

我也将答案设置为整数 '0,1,2,3' 但现在它甚至没有将它们连接到正确的答案:(

我有一个“问题”类,其中包含:

public Question(string q, string[] answersList, string typeOfQuestion, int correctAnswer)

然后我在程序中创建问题对象

new Question("What colour is the sky?", 
    new string[] { "A. Pink", "B. Blue", "C. Purple", "D.Yellow" },
    Question.multipleChoice, B );

标签: c#arraysclassobjectindexing

解决方案


这是一个小控制台应用程序,它为数组中的项目生成字母,并接受用户输入(大写或小写)并将其转换回数字。

关键是 'a' 是 65 而 'A' 是 ASCII 的 97,你可以用 . 将数字转换为字母Convert.ToChar(i)。控制台提供 ASCII 值,但您可以找到 ASCII 值和一个字母(int)Char.GetNumericValue('a');

class Program
{
    static void Main(string[] args)
    {
        var q1 = new Question("What colour is the sky?", new string[] { "Pink", "Blue", "Purple", "Yellow" }, "multipleChoice", 1);

        AskQuestion(q1);
    }

    private static void AskQuestion(Question q)
    {
        Console.WriteLine(q.Prompt);
        for (var i = 0; i < q.AnswersList.Length; i++)
        {
            Console.WriteLine($"{Convert.ToChar(65 + i)} - {q.AnswersList[i]}");
        }

        var answer = Console.ReadKey(true);

        if (answer.KeyChar == 65 + q.CorrectAnswer ||
            answer.KeyChar == 97 + q.CorrectAnswer)
        {
            Console.WriteLine("Correct");
        }
        else
        {
            Console.WriteLine("Wrong");
        }
    }

    private class Question
    {
        public string Prompt { get; }
        public string[] AnswersList { get;  }
        public string TypeOfQuestion { get; }
        public int CorrectAnswer { get;  }

        public Question(string prompt, string[] answersList, string typeOfQuestion, int correctAnswer)
        {
            this.Prompt = prompt;
            this.AnswersList = answersList;
            this.TypeOfQuestion = typeOfQuestion;
            this.CorrectAnswer = correctAnswer;
        }
    }
}

推荐阅读