【问题标题】:Using a for loop when calling a method调用方法时使用 for 循环
【发布时间】:2016-02-25 18:04:10
【问题描述】:

我在方法中使用 for 循环将结果传送到主函数。我正在尝试使用 for 循环来获取一年中的月份并将其传递给 main 函数的输出。

我在 for 循环中嵌套了一个 if 循环,我觉得这可能是多余的,因为 for 循环无论如何都会算到最后。 这可能是代码中一个足够基本的问题,但我已经盯着它看了很长时间,以至于我认为它已经耗尽了。

所有月份的输出都返回“不存在”,而不是选择相关月份。如何从 for 循环中选择相关月份,或者我目前的编码方式是否可行?

namespace Month_Function_Call
    {
class Program
{
    public static String month_name(int month)
    {
        String result;
        result = "a";
        for (int i = 0; i < 12; ++i )
        {
            if (i == 0)
            {
                result = "January";
            }
            if (i == 1)
            {
                result = "February";
            }
            if (i == 2)
            {
                result = "March";
            }
            if (i == 3)
            {
                result = "April";
            }
            if (i == 4)
            {
                result = "May";
            }
            if (i == 5)
            {
                result = "June";
            }
            if (i == 6)
            {
                result = "July";
            }
            if (i == 7)
            {
                result = "August";
            }
            if (i == 8)
            {
                result = "September";
            }
            if (i == 9)
            {
                result = "October";
            }
            if (i == 10)
            {
                result = "November";
            }
            if (i == 11)
            {
                result = "December";
            }
            else
            {
                result = "N/A";
            }


        }
            return result;
    }
    static void Main(string[] args)
    {
        Console.WriteLine("Month 1: " + month_name(1));
        Console.WriteLine("Month 2: " + month_name(2));
        Console.WriteLine("Month 3: " + month_name(3));
        Console.WriteLine("Month 4: " + month_name(4));
        Console.WriteLine("Month 5: " + month_name(5));
        Console.WriteLine("Month 6: " + month_name(6));
        Console.WriteLine("Month 7: " + month_name(7));
        Console.WriteLine("Month 8: " + month_name(8));
        Console.WriteLine("Month 9: " + month_name(9));
        Console.WriteLine("Month 10: " + month_name(10));
        Console.WriteLine("Month 11: " + month_name(11));
        Console.WriteLine("Month 12: " + month_name(12));
        Console.WriteLine("Month 43: " + month_name(43));
        Console.ReadKey();
    }
}

【问题讨论】:

  • 为什么要循环而不是在if 语句中比较month
  • 你遇到了什么问题?您实际上在寻求什么帮助?如果您在进行代码审查,那么 codereview.stackexchange.com 存在并且可能是解决问题的更好地方(但前提是您的代码确实有效)。
  • 您的方法中不需要循环,您需要Main 中的循环将月份1 传递给12。还要查看Dictionary&lt;TKey,TValue&gt;,以便您可以在您的方法中使用if 语句。另外,已经有一些方法可以根据数字获取月份名称。最后一件事是你需要if ... else ... if 来解决无效的选择,你也可以在这里使用switch
  • @Damo,您的主要问题是您有一个方法接受代表月份的int,但您从不引用该对象。您的方法应该使用其参数中的信息来计算结果。

标签: c#


【解决方案1】:

使用 Swith-Case 语句是这里的最佳选择。

但是,如果你不知道如何使用它,你应该删除 For 语句,因为它完全是无意义的。

 //for (int i = 0; i < 12; ++i )
    //{

    //}

【讨论】:

    【解决方案2】:

    改为这样做

    string[] months = new string[12] {"January", "February", "March" }; // Input all months to this array
    
    if (index <= -1 || index > 12) return "N/A";
    return months[index];
    

    将此代码插入 getMonthName() 函数

    【讨论】:

    • 我看到你的43个测试用例,让我编辑适合那个的答案,嗯。
    • 谢谢你,这比我输入的废话更有意义!我知道这将是我错过的一些简单的事情
    • 随便return index &gt;= 0 &amp;&amp; index &lt; 12 ? months[index] : "N/A";
    • @juharr 你说得对,这更适合它,我只是这样做,以便 OP 阅读并理解代码的执行情况。
    • @TuukkaX 是的,我实际上在您添加 if 之前添加了该评论,尽管您当前的逻辑倒退了。
    【解决方案3】:

    我认为使用DateTimeFormat 中的GetMonthName 会是一种更好的方法。这将为您提供用户活跃文化中的名称。 (您当然可以将其硬编码为您喜欢的任何文化)然后ToTitleCase 将第一个字符设为大写。

    public static String month_name(int month)
    {
       if(month < 1 || month > 12) 
          return "N/A";
       var culture = CultureInfo.CurrentCulture;
       var name = culture.DateTimeFormat.GetMonthName(month);
       return culture.TextInfo.ToTitleCase(name);
    }
    

    【讨论】:

    • 首先,OP 使用从零开始的月份名称索引,这使用从 1 开始的索引。其次,这将返回一个值为 13 的空字符串,并为小于 1 和大于 13 的值引发异常。
    • @juharr 至于从零开始的索引,如果您查看他的 Main 方法,他的函数似乎是错误的,它假定 1 是第一个月。
    • @juharr 你是对的,这是我在你提到它之后发现的一个错误,我花了一段时间才弄清楚为什么我得到 N\A 两个月而不是一个但它是索引那是错误的
    • @Magnus 是的,我也注意到了这一点,并要求 OP 澄清
    【解决方案4】:

    在我看来,在这种情况下,您应该省略在 for 循环中使用这么多 if 语句,因为它的可读性不够,更好的方法是创建一个字符串类型的数组,该数组将包含所有月份的名称和迭代这个数组。你的代码是这样的:

    public static String month_name(int month) {
            String result;
            result = "a";
            // for the sake of readability I have split the line
            String[] allMonths = { 
                                  "N/A", "January", "February", "March", "April",
                                  "May", "June", "July", "August", "September", 
                                  "October", "November", "December" 
                              };
            if (month >= 0 && month <= 12)
                result = allMonths[month];
            else
               result = "N/A";
    
            return result;
        }
    
        static void Main(string[] args) {
            Console.WriteLine("Month 1: " + month_name(1));
            Console.WriteLine("Month 2: " + month_name(2));
            Console.WriteLine("Month 3: " + month_name(3));
            Console.WriteLine("Month 4: " + month_name(4));
            Console.WriteLine("Month 5: " + month_name(5));
            Console.WriteLine("Month 6: " + month_name(6));
            Console.WriteLine("Month 7: " + month_name(7));
            Console.WriteLine("Month 8: " + month_name(8));
            Console.WriteLine("Month 9: " + month_name(9));
            Console.WriteLine("Month 10: " + month_name(10));
            Console.WriteLine("Month 11: " + month_name(11));
            Console.WriteLine("Month 12: " + month_name(12));
            Console.WriteLine("Month 43: " + month_name(43));
            Console.ReadKey();
        }
    

    希望对您有所帮助:)

    【讨论】:

      【解决方案5】:

      您可以使用switch 使这个更清洁

       switch (month)
              {
                  case 0: return "January";
                  case 1: return "February";
                  case 2: return "March";
                  case 3: return "April";
                  case 4: return "May";
                  case 5: return "June";
                  case 6: return "July";
                  case 7: return "August";
                  case 8: return "September";
                  case 9: return "October";
                  case 10: return "November";
                  case 11: return "December";
                  default: return "N/A";
              }
      

      【讨论】:

        【解决方案6】:

        不要使用循环和 if-else。你需要的是字典。

        static Dictionary<int, string> _monthName = new Dictionary<int, string>
        {
            {1,"January" }, // if zero based start from 0
            {2,"February" },
            {3,"March" },
            {4,"April" },
            {5,"May" },
            {6,"June" },
            {7,"July" },
            {8,"August" },
            {9,"September" },
            {10,"October" },
            {11,"November" },
            {12,"December" },
        };
        
        private static string GetMonthName(int i)
        {
            var result = "";
            if (_monthName.TryGetValue(i, out result))
            {
                return result;
            }
            return "N/A";
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Month 1: " + GetMonthName(1));
            Console.WriteLine("Month 2: " + GetMonthName(2));
            Console.WriteLine("Month 3: " + GetMonthName(3));
            Console.WriteLine("Month 4: " + GetMonthName(4));
            Console.WriteLine("Month 5: " + GetMonthName(5));
            Console.WriteLine("Month 6: " + GetMonthName(6));
            Console.WriteLine("Month 7: " + GetMonthName(7));
            Console.WriteLine("Month 8: " + GetMonthName(8));
            Console.WriteLine("Month 9: " + GetMonthName(9));
            Console.WriteLine("Month 10: " + GetMonthName(10));
            Console.WriteLine("Month 11: " + GetMonthName(11));
            Console.WriteLine("Month 12: " + GetMonthName(12));
            Console.WriteLine("Month 43: " + GetMonthName(43));
            Console.ReadKey();
        }
        

        【讨论】:

          猜你喜欢
          • 2019-06-16
          • 1970-01-01
          • 2018-11-07
          • 1970-01-01
          • 1970-01-01
          • 2020-05-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多