0

我正在尝试制作一个潜在的两个玩家程序,其中一个用户提示输入一个问题,然后提示输入对该问题的答案,这两个问题都将存储在一个二维数组中。第一位玩家最多可以输入10个问题。在存储问题和答案后,我希望能够让第二个玩家回答第一个玩家问的问题。C#在字符串数组中存储用户输入

现在,我被困在一个非常基本的部分,它将问题和答案存储在数组中。

这里是我迄今为止我的第一类代码:

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; 
     } 
    } 

我的第二类:

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); 
    } 
} 

我把用户输入他们的第一个答案后,得到相同的错误消息 “对象引用未设置为对象实例“

回答

7

您需要初始化您的newquestion实例:

MakeOwnQuestion newquestion = new MakeOwnQuestion(); 

我也建议你使用而不是Length一个多维数组:

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

或者更好的是,仅仅是某种类型的,例如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)); 
    } 
} 
+0

谢谢,这是非常有用的,它的工作!我想我会继续使用多维数组,因为这是我熟悉的,但我会做一些练习程序与列表类 – user2908363

+0

@ user2908363很高兴我能帮上忙。如果您有任何其他问题可以随时询问SO。快乐编码:) –

相关问题