Search code examples
c#arraysmultidimensional-arrayconsole-applicationstoring-information

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. 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"


Solution

  • You need to initialize your newquestion instance:

    MakeOwnQuestion newquestion = new MakeOwnQuestion();
    

    I'd also recommend you use GetLength rather than Length for a multidimensional array:

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

    Or better yet, just a List<T> of some type, e.g. 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));
        }
    }