【发布时间】: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<TKey,TValue>,以便您可以在您的方法中使用if语句。另外,已经有一些方法可以根据数字获取月份名称。最后一件事是你需要if ... else ... if来解决无效的选择,你也可以在这里使用switch。 -
@Damo,您的主要问题是您有一个方法接受代表月份的
int,但您从不引用该对象。您的方法应该使用其参数中的信息来计算结果。
标签: c#