【问题标题】:Compare int input to position of array将 int 输入与数组的位置进行比较
【发布时间】:2015-04-27 20:34:45
【问题描述】:

这里是 C# 菜鸟,尝试用不同的方法解决一个基本问题。我想将一个参数传递给一个方法,并在该方法中循环遍历几个月的数组。如果参数等于数组的位置,我想返回那个数组位置的字符串。

我尝试了以下方法:

class Month
{
    private int month;

    public string strMonth(int month)
    {
        this.month = month;

        string[] months = { " ", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

        for (int i = 0; i < months.Length; i++)
        {
            if (month == Array.IndexOf(months, i))
            {
                return months[i];
            }
        }

        return "check fails";
    }
}

对于我正在使用的驱动程序

class Program
{
    static void Main(string[] args)
    {
        Month testMonth = new Month();

        Console.WriteLine(testMonth.strMonth(2));

        Console.ReadKey();
    }
}

但是,我总是在控制台中登录check fails。我是在正确的道路上还是菜鸟占了上风,而我这样做完全错了?我也对块级作用域感到困惑(我认为这就是 C# 所做的?)。我来自 JS 背景,习惯于函数级别范围。即使我的检查通过,添加return "check fails" 是否总是会执行?

【问题讨论】:

  • 您知道“一月”必须插入 0 对吗?
  • 是的,我知道这一点。我有一个空字符串作为 [0] 来欺骗支票。谢谢你指出这一点。不过,这与我的问题无关。

标签: c# arrays


【解决方案1】:

更简洁的方法是使用字典。比如:

class Month
{
    public string strMonth(int month)
    {
        var months = new Dictionary<int, string>
        {
            {1, "Jan"},
            {2, "Feb"},
            {3, "March"},
            {4, "April"},
            {5, "May"},
            {6, "June"},
            {7, "July"},
            {8, "Aug"},
            {9, "Sept"},
            {10, "Oct"},
            {11, "Nov"},
            {12, "Dec"}
        };

        var monthString = "check fails";
        if (months.ContainsKey(month))
        {
            monthString = months[month];
        }
        return monthString;
    }
}

【讨论】:

  • 不客气。它还降低了复杂性,因为您不必遍历数组
  • 如果问题真的是从数字中获取月份名称,那么stackoverflow.com/questions/3184121/… 可能会很有趣,并且还具有为不同文化等工作的优势。
  • @Chris 真的不是,我只是想尝试将 int 参数与数组中的位置匹配,这似乎是一个很好的用例。
  • @Dann:我确实怀疑这一点,但是当您接受一个不是关于按位置将事物从数组中取出的答案时,我变得不确定。即接受的答案似乎保存了问题的“按整数获取月份”而不是“从现有数组中获取值”部分,甚至没有解决您的代码不起作用的原因。只要你好,那么一切都好。 :)
  • @Chris 我看到了其他几个答案,这些答案似乎可以解决我的代码无法正常工作的原因,并且更多地符合我最初的问题,但我最喜欢这个解决方案。我以前从未使用过字典,对我来说,在这种情况下它似乎是一个不错的选择:)
【解决方案2】:

阅读Array.IndexOf 的文档将清楚哪里出了问题:

搜索指定对象并返回其第一个的索引 在一维数组中出现。

https://msdn.microsoft.com/en-us/library/7eddebat(v=vs.110).aspx

所以你正在做的是在数组中搜索 int 2 并没有找到它,所以返回 -1 当然永远不会等于你的输入。

做你想做的最好的方式就是return months[month]

【讨论】:

    【解决方案3】:

    如果您只需要月份名称,可以使用 DateTimeFormatInfo.GetMonthName()

    例如 public string strMonth(int month) { return System.Globalization.CultureInfo .CurrentCulture.DateTimeFormat.GetMonthName(month); }

    【讨论】:

      【解决方案4】:

      这样做应该可以防止非法索引尝试访问数组并发送异常消息。

      class Month
      {
          private int month;
      
          public string strMonth(int month)
          {
              this.month = month;
      
              string[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
              if (month <= months.Length && month > 0)
                  return months[i-1];
          }
          return "check fails";
      }
      

      【讨论】:

        【解决方案5】:

        您有很多不必要的代码来将索引转换为数组元素。你真的是想太多这个问题了。

        public string strMonth(int index)
        {
            string[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
            return months[index]; //0-index array (Jan = 0)
        }
        

        如果您尝试将基于 1 的索引 (Jan = 1) 转换为字符串,只需使用 return months[index - 1]; 从索引中减去 1。然后你避免将空白字符串作为可能的结果。

        和往常一样,请考虑您希望在哪里处理可能的 ArrayIndex 异常。
        如果你想验证这个方法中的索引(而不是让异常冒泡到调用方法),你可以添加这个检查:

        public string strMonth(int index)
        {
            if (index < 0|| index > 11) //or 1, 12 for the 1-indexed version
                 return "Failed.";
        
            string[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
            return months[index]; //0-indexed array (Jan = 0)
        }
        

        【讨论】:

          【解决方案6】:
          using System;
          
          namespace Test
          {
              class MainClass
              {
                  public static void Main (string[] args)
                  {
                      string[] data = new string[] { "a", "b", "c", "d", "e", "f" };
          
                      int input = Convert.ToInt32 (Console.ReadLine ());
                      try {
                          Console.WriteLine (data [input]);
                      } catch (IndexOutOfRangeException) {
                          Console.WriteLine ("Invalid input.");
                      }
                  }
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2015-10-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-04-14
            • 1970-01-01
            • 2016-05-24
            相关资源
            最近更新 更多