0

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"

1 Answer 1

7

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));
    }
}
2
  • Thank you, that is very helpful and it worked! I think I am going to continue with using the multidimensional array only because that is what I am familiar with, but I will do some practice programs with the List<T> Class Oct 23, 2013 at 17:08
  • @user2908363 Glad I could help. If you have any other issues feel free to ask on SO. Happy coding :)
    – p.s.w.g
    Oct 23, 2013 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.