簡體   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();

現在,當我想輸入名稱時,它只會打印輸入的第一個名稱!

就像我有5個名字一樣,在最后一行

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

它只是打印出第一個名字!

您也想在最后做一個循環

for循環或foreach ,當前使用Console.WriteLine()是使用string.Format()重載

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

將字符串與所需的分隔符連接在一起,然后再將它們傳遞到writeline。

使用string.Join這樣做。

將數組傳遞給WriteLine會使您認為您正在傳遞帶有要格式化的值的數組。

您必須做一個循環。

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