J.Gold J.Gold - 2 months ago 9
C# Question

Outputing a string array

I have 3 methods to 1. Take in strings as an array [zipCodes], 2. Output a menu for the user and 3. display the string array back to the user. The first 2 options are working and after testing I can say that the array is working and taking in strings, however I am having bother displaying them back to the user.

I have used this method with ints, it makes me think that the [i] is only for 1 character, an explanation would be greatly appreciated.

// Here is the code so far

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

Answer

You should assign input into the array items:

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