简体   繁体   English

C#将用户输入存储在字符串数组中

[英]C# storing user input in string array

I am trying to make a potential two player program where one user is prompted to enter a question and then prompted to enter the answer to that question both of which will be stored in a two dimensional array. 我试图制作一个潜在的两人游戏程序,在该程序中,一个用户被提示输入一个问题,然后被提示输入该问题的答案,这两个问题都将存储在二维数组中。 The first player will be able to enter up to 10 questions. 第一位玩家最多可以输入10个问题。 After both the question and answer to that question are stored, I would like to then be able to have the second player prompted to answer the questions the first player asked. 在存储问题和对该问题的答案之后,我希望能够提示第二位玩家回答第一位玩家提出的问题。

Right now I'm stuck at a pretty basic part which is storing the questions and answers in the array. 现在,我停留在一个非常基本的部分,它将问题和答案存储在数组中。

Here is the code I have so far my first class: 这是到目前为止我第一堂课的代码:

class MakeOwnQuestion
{
    string question;
    string answer;
    string[,] makequestion = new string[10, 2];

    public void MakeQuestion(string question, string answer, int index)
    {
        if (index < makequestion.Length)
        {
            makequestion[index, 0] = question;
            makequestion[index, 1] = answer;
        }
    }

My second class: 我的第二堂课:

class MakeOwnQuestionUI
{
    MakeOwnQuestion newquestion;

    public void MainMethod()
    {
        PopulateArray();
    }

    void PopulateArray()
    {
        string question;
        string answer;
        Console.WriteLine("Enter Your Question: ");
        question = Console.ReadLine();

        Console.WriteLine("Enter Your Answer: ");
        answer = Console.ReadLine();

        newquestion.MakeQuestion(question, answer, 0);

        Console.WriteLine("Enter Your Question: ");
        question = Console.ReadLine();

        Console.WriteLine("Enter Your Answer: ");
        answer = Console.ReadLine();

        newquestion.MakeQuestion(question, answer, 1);
    }
}

I keep getting the same error message after the user enters their first answer "Object reference not set to an instance of an object" 用户输入第一个答案“对象引用未设置为对象的实例”后,我不断收到相同的错误消息

You need to initialize your newquestion instance: 您需要初始化newquestion实例:

MakeOwnQuestion newquestion = new MakeOwnQuestion();

I'd also recommend you use GetLength rather than Length for a multidimensional array: 我还建议您对多维数组使用GetLength而不是Length

if (index < makequestion.GetLength(0))
{
    ...
}

Or better yet, just a List<T> of some type, eg Tuple<string, string> : 或者更好的是,只是某种类型的List<T> ,例如Tuple<string, string>

class MakeOwnQuestion
{
    List<Tuple<string, string>> makequestion = new List<Tuple<string, string>>();

    public void MakeQuestion(string question, string answer, int index)
    {
        makequestion.Add(Tuple.Create(question, answer));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM