带有数组的Q& A程序

时间:2016-04-05 19:33:02

标签: c# arrays

您好我正在学习C#,并想知道如何为以下Q& A创建数组。

这是一个简单的q& a程序,我试图编写以便在C#中发展我的技能。谢谢!

 Console.WriteLine("What's your favorite baseball team? ");
        string baseball = Console.ReadLine();

        Console.WriteLine("How old are you? ");
        string age = Console.ReadLine();

        Console.WriteLine("Where do you live? ");
        string home = Console.ReadLine();

        Console.WriteLine("Aside from Baseball, what other sports do you love? ");
        string sports = Console.ReadLine();
    } 

2 个答案:

答案 0 :(得分:1)

您可以在初始化时将项添加到数组中,如下所示:

string[] myArray = {baseball, age, home, sports};

或者您可以初始化数组,然后像这样添加项目:

string[] myArray = new string[4];
myArray[0] = baseball;
myArray[1] = age;
myArray[2] = home;
myArray[3] = sports;

但是,正如上面的答案中所述,最好使用根据您的需求扩展的通用列表(您不必在初始化时指示元素的最大数量),如下所示:< / p>

List<string> myList =  new List<string> { baseball, age, home, sports };

或者像这样:

List<string> myList =  new List<string>();
myList.Add(baseball);
myList.Add(age);
myList.Add(home);
myList.Add(sports);

列表中美丽的部分是您可以稍后添加其他元素,它会自动扩展,例如:

myList.Add("Another response will go here");

通用集合也更快。

答案 1 :(得分:1)

我假设您只想将这些操作的结果存储在数组中。如果是这种情况,那么您只需要实例化一个新数组来保存您的每个响应:

string[] answers = new string[3];

Console.WriteLine("What's your favorite baseball team? ");
string baseball = Console.ReadLine();
// Store your first answer in the first index of the array
answers[0] = baseball;

Console.WriteLine("How old are you? ");
string age = Console.ReadLine();
// Store your age in the second index, etc.
answers[1] = age;

// Continue with your other questions here

或者你可以在拥有所有变量之后在最后构建数组:

string[] answers = { baseball, age, ... };

然后,您可以通过数组中的索引引用这些值:

string sentence = "I am " + answers[1] + " years old";

如果您需要将项目存储在可以动态调整以满足您需求的集合中,您可以考虑使用List,同样如果您需要按名称引用您的值(例如&#34;棒球& #34;,&#34;年龄&#34;等),然后你可以使用Dictionary