输出字符串数组

时间:2016-09-30 20:46:25

标签: c# arrays string output display

我有3个方法1.将字符串作为数组[zipCodes],2。输出用户的菜单,3。将字符串数组显示给用户。前两个选项正在运行,经过测试后,我可以说数组正在工作并接受字符串,但是我很难将它们显示给用户。

我已经使用了这个方法,它让我认为[i]仅适用于1个字符,我将非常感谢您的解释。

//到目前为止这是代码

static void Main(string[] args)
        {
            string[] zipCodes = new string[10];
            string zCounter;

            for (int i = 0; i < zipCodes.Length; i++)
            {
                Console.WriteLine("Please enter 10 destinations:");
                zCounter = Convert.ToString(Console.ReadLine());
                zCounter = zipCodes[i];
            }

            int sentinalNo;

            Console.Clear();
            Console.WriteLine("Please enter from the following options: ");
            Console.WriteLine("1. Display order zipcodes.");
            Console.WriteLine("2. Search zipcode.");
            Console.WriteLine("3. Exit.");
            sentinalNo = Convert.ToInt32(Console.ReadLine());

            while (sentinalNo != 3)
            {
                switch (sentinalNo)
                {
                    case 1:
                        DisplayZips(zipCodes);
                        break;
                }

            }


        }

        private static void DisplayZips(string[] zipCodes)
        {
            for (int i = 0; i < zipCodes.Length; i++)
            {
                // Why doesnt this work?
                Console.WriteLine(zipCodes[i]);
            }

1 个答案:

答案 0 :(得分:2)

您应该将输入分配给数组项:

        // array of 10 strings each of them is null
        string[] zipCodes = new string[10];
        ... 

        for (int i = 0; i < zipCodes.Length; i++)
        {
            Console.WriteLine("Please enter 10 destinations:");
            // Convert.ToString is redundant here
            zCounter = Convert.ToString(Console.ReadLine());

            // swapped: user input is assigned to array items
            zipCodes[i] = zCounter;
        }