используя несколько классов в программе - PullRequest
2 голосов
/ 04 мая 2020

Пытаюсь отсортировать мою программу викторины по классам, но я не могу понять, как их инициировать и вызывать содержимое в дальнейшем. Я хочу добавить свои «вопросы» в их собственный класс, затем позвонить им позже и в конечном итоге сделать то же самое с моими «вариантами ответов и ответов». Мне пришлось вырезать часть кода, чтобы он мог публиковаться на этом форуме. Любая помощь очень ценится!

namespace ConsoleApp3
{
    class Questions
    {
        public Questions();
        string[] questions =    //question array
            {
            "1. What year is it in the opening scene of the movie?", //mult choice
            "2. Peter Quill’s alias is “Star Prince”", //true false

        };

        public string[] Questions { get => questions; set => questions = value; }
    }
    class Program
    {
        private const bool V = false;

        static void Main(string[] args)
        {
            int correct = 0;
            int wrong = 0;
            string quizTitle = "How well do you know the Guardians of the Galaxy?";
            string prompt = "Please make a selection...";



            string[] answerChoices =    //answer choices array
            {
            "   a. 1981\n   b. 1988\n   c. 1985\n   d. 1990",
            "   a. True\n   b. False",

        };
            string[] answers =  //correct answer array
            {
            "b",
            "b",

        };
            //array for flagging incorrect answers
            bool[] redoQuestion =
            {
            false,
            false,

        };                      //start of program

            string input;
            for (int x = 0; x < questions.Length; ++x)      //for loop to ask & check questions for initial attempt
            {
                do
                {           //checking for valid input
                    Console.WriteLine(Questions.ToString questions[x]);
                    Console.WriteLine(answerChoices[x]);
                    Console.WriteLine(prompt);
                    input = Console.ReadLine();
                } 

Ответы [ 3 ]

2 голосов
/ 04 мая 2020

Существует много способов структурировать эти данные, но есть разумный вариант:

public class Answer
{
    public string Option;
    public string Text;
}

public class Question
{
    public string Text;
    public string CorrectOption;
    public Answer[] Answers;
}

Затем вы инициализируете свои данные следующим образом:

var questions = new []
{
    new Question()
    {
        Text = "What year is it in the opening scene of the movie?",
        CorrectOption = "b",
        Answers = new []
        {
            new Answer() { Option = "a", Text = "1981" },
            new Answer() { Option = "b", Text = "1988" },
            new Answer() { Option = "c", Text = "1985" },
            new Answer() { Option = "d", Text = "1990" },
        }
    },
    new Question()
    {
        Text = "Peter Quill’s alias is “Star Prince”",
        CorrectOption = "b",
        Answers = new []
        {
            new Answer() { Option = "a", Text = "True" },
            new Answer() { Option = "b", Text = "False" },
        }
    }
};

Прелесть этого в том, что он хорошо держит каждый вопрос вместе с ответами и указанием того, какой ответ правильный.

0 голосов
/ 04 мая 2020
    static void Main(string[] args)
    {
        var quiz = new Quiz()
        {
            Title = "My quiz",
            questions = new List<Question>()
            {
                new Question() {
                    Answers = "1. wrong \r\n 2.correct \r\n 3. wrong",
                    Answer = 2
                },
                new Question() {
                    Answers = "1. wrong \r\n 2.correct \r\n 3. wrong",
                    Answer = 2
                }
            }
        };

        int correct = 0;

        foreach (var question in quiz.questions)
        {
            Console.WriteLine(quiz.Title);
            Console.WriteLine(question.Answers);
            Console.WriteLine("Enter number: ");
            int input = int.Parse(Console.ReadLine());
            if (input == question.Answer) correct++;
        }

        Console.WriteLine("Number of correct answers is " + correct);

    }


    public class Quiz
    {
        public string Title { get; set; }
        public List<Question> questions { get; set; }

    }

    public class Question
    {
        public string Answers { get; set; }
        public int Answer { get; set; }
    }
0 голосов
/ 04 мая 2020

ваша система должна выглядеть примерно так

class Question
{
    int Id {get; set;}
    string Text {get; set;}
    Answer[] Answers {get; set;}
}

class Answer
{
    int Id {get; set;}
    int QuestionId {get; set;}
    string Text {get; set;}
    bool IsCorrect {get; set;}
}

class UserAnswer
{
    Question QuestionId {get; set;}
    Timespan TimeSpent {get; set;}
    bool Skipped {get; set;}
    int[] UserSelection {get; set;};
}


static class AnswerEvaluator
{
    static EvalResult Evaluate(UserAnswer ua)
    {
        // your scoring logic goes here
    }
}

class ScoreReport
{
    ScoreReport (UserAnswer[] answers, int passingGrade)
    {
        // . . . . 
    }

    int PercentCorrect {get; set;}
    int QuestionsAnswered {get; set;}
    int QuestionsSkipped {get; set;}
    int TotalScore {get; set;}
    Timespan TotalTime {get; set;}
    bool Passed {get; private set;}


    void EvaluateAll()
    { 
        // . . . .
    }
}

...