【问题标题】:How do I fix "System.String[]" Error in C# ? (using arrays + For loop)如何修复 C# 中的“System.String[]”错误? (使用数组 + For 循环)
【发布时间】:2013-12-10 00:15:58
【问题描述】:

好的,我正在尝试制作一个基本上使用 for 循环来显示星期几的程序,我的代码看起来很好,运行良好,但是当我碰巧运行它时......它出现“The星期几是 System.String[]".. 而我希望它显示星期几是星期一...星期几是星期二...星期三.. 等等。

到目前为止,这是我为此编写的代码:

        //Declare variables
        int iDays;

        //Declare array
        const int iWEEK = 7;
        string[] sDays = new string[iWEEK] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

        //Display the days of the week
        for (iDays = 0; iDays < iWEEK; iDays++)
        {
            Console.WriteLine("The day of the week is " + sDays);
        }

        //Prevent program from closing
        Console.WriteLine();
        Console.WriteLine("Press any key to close");
        Console.ReadKey();

【问题讨论】:

    标签: c# arrays loops for-loop


    【解决方案1】:

    你必须在数组中打印一个值,而不是数组本身。

    请改用sDays[iDays]。这将检索数组sDays 中位置iDays 的值。

    【讨论】:

    • 非常感谢,除此之外我几乎尝试了所有其他方法。我现在感觉很愚蠢,我正在尝试 sDays[iWEEK] 也出现了一个严重错误,谢谢!
    • 我们都去过那里,没问题。 sDays[iWEEK] 出现错误,因为它会尝试访问索引 7。您的数组只有索引 0 到 6。
    • sDays[iWEEK] 会给你Index was outside the bounds of the array.,因为你会为它提供7,这是一个比数组中存在的索引更高的索引。数组从索引0 开始,所以6 将是您可以使用的最高索引,但它仍然是第7 个值!
    • @user2985995 如果它解决了您的问题,请考虑接受答案。 meta.stackexchange.com/a/5235/161449
    • 啊,好的,我现在明白了,谢谢你的帮助,感激:)
    【解决方案2】:

    您绝对不需要数组来显示工作日的名称。它们已经存在于系统中:

    for (int i = 1; i <= 7; i++)
    {
        DateTime dt = DateTime.Now;
        dt = dt.AddDays(i - (int)DateTime.Now.DayOfWeek);
        Console.WriteLine(dt.ToString("dddd", System.Globalization.CultureInfo.CreateSpecificCulture("en-US")));
    }
    

    【讨论】:

      【解决方案3】:

      //声明变量 int iDays;

          //Declare array
          const int iWEEK = 7;
          string[] sDays = new string[iWEEK] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
      
          //Display the days of the week
          for (iDays = 0; iDays < iWEEK; iDays++)
          {
              Console.WriteLine("The day of the week is " + sDays[iDays]);
          }
      
          //Prevent program from closing
          Console.WriteLine();
          Console.WriteLine("Press any key to close");
          Console.ReadKey();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 2019-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多