简体   繁体   English

C#中的数组问题

[英]issues with Arrays in C#

Console.WriteLine("Please enter your number of the Names : ?");
int x = Convert.ToInt32(Console.ReadLine());
string[] names = new string[x];
for (int i = 0; i < x; i++)
{
    Console.Write("Enter Name no.{0} :  ", i + 1);
    names[i] = Console.ReadLine();
}

Console.WriteLine("the items are {0}", names);
Console.ReadKey();

Now when I want to type down the names, it just prints the first Name entered! 现在,当我想输入名称时,它只会打印输入的第一个名称!

Like if I have 5 names, in the last line in the 就像我有5个名字一样,在最后一行

Console.WriteLine("the items are {0}", names);

it just prints out the 1st name! 它只是打印出第一个名字!

You'll want to do a loop at the end as well 您也想在最后做一个循环

Either a for loop or a foreach , the current way you are using Console.WriteLine() is using the string.Format() overload for循环或foreach ,当前使用Console.WriteLine()是使用string.Format()重载

foreach (string name in names)
{
    // Write out here
    Console.WriteLine(name);
}

Join the strings together with the separator you want, before passing them to writeline. 将字符串与所需的分隔符连接在一起,然后再将它们传递到writeline。

Use string.Join to do so. 使用string.Join这样做。

Passing an array to WriteLine makes out think you are passing an array with values to format. 将数组传递给WriteLine会使您认为您正在传递带有要格式化的值的数组。

You have to do a loop. 您必须做一个循环。

Console.Write("the items are");
for (int i = 0; i < names.Length; ++i)
{
    Console.Write(" ");
    Console.Write(names[i]);
}
Console.WriteLine();
//Console.WriteLine("the items are {0}.", String.Join(", ", names));
string argsFormat = ( 1 < x) ?
    String.Join(", ", Enumerable.Range(0, x).Select(n => "{" + n + "}").ToArray())
    .Replace(", {" + (x-1) + "}", " and {" + (x-1) + "}") + "." 
    :
    argsFormat = "{0}.";
Console.WriteLine("the items are " + argsFormat , names);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM