简体   繁体   中英

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

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

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.

Use string.Join to do so.

Passing an array to WriteLine makes out think you are passing an array with values to format.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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