输出字符串数组
Outputting a string array
我有 3 种方法:1. 将字符串作为数组 [zipCodes],2. 为用户输出菜单,3. 将字符串数组显示给用户。前 2 个选项正在运行,测试后我可以说数组正在运行并接收字符串,但是我无法将它们显示给用户。
我对整数使用过这种方法,这让我觉得 [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]);
}
您应该将输入分配到数组项中:
// 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;
}
我有 3 种方法:1. 将字符串作为数组 [zipCodes],2. 为用户输出菜单,3. 将字符串数组显示给用户。前 2 个选项正在运行,测试后我可以说数组正在运行并接收字符串,但是我无法将它们显示给用户。
我对整数使用过这种方法,这让我觉得 [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]);
}
您应该将输入分配到数组项中:
// 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;
}