重复if else语句

时间:2016-03-22 23:49:03

标签: c# if-statement

如果在if语句实现之后如何实现它将不会执行,我可以重新输入另一组数字?...停止它虽然我会让它输入-1退出。

static void Main(string[] args)
{
    {
        // first enter 2016, then 2000, then 2015 and get multiple results
        int Year;
        Console.WriteLine("Please enter a year: ");
        Year = Convert.ToInt32(Console.ReadLine());
        if ((Year % 4 == 0) && (Year % 100 != 0 || Year % 400 != 0)) // <--- entered 2016
        {
            Console.WriteLine("The Year you have entered is a Leap Year {0}.", Year);
        }
        if ((Year % 4 == 0) && (Year % 100 == 0)) // <--- year 2000
        {
            Console.WriteLine("the 2000 works", Year);
        }
        if ((Year % 5 == 0) && (Year % 100 != 0)) // <--- year 2015
        {
            Console.WriteLine("2015 works", Year);
        }
        else
        {
            // startover
        }
        Console.ReadLine();
    }
}

2 个答案:

答案 0 :(得分:1)

有点不清楚,因为你要重复这个过程,直到你按-1,你可以做这样的事情。

int年;

do  
{
    Console.WriteLine("Please enter a year: ");
    if(!int.TryParse(Console.ReadLine(), out Year))
    {
          Console.WriteLine("invalid input");
          continue;
    }

    if ((Year % 4 == 0) && (Year % 100 != 0 || Year % 400 != 0)) // <--- entered 2016
    {
        Console.WriteLine("The Year you have entered is a Leap Year {0}.", Year);
    }
    if ((Year % 4 == 0) && (Year % 100 == 0)) // <--- year 2000
    {
        Console.WriteLine("the 2000 works", Year);
    }
    if ((Year % 5 == 0) && (Year % 100 != 0)) // <--- year 2015
    {
        Console.WriteLine("2015 works", Year);
    }


}   while(Year != -1);

//Console.ReadLine(); not required.

工作Code

答案 1 :(得分:1)

如果您只是测试输入的年份是否是闰年,您可以使用DateTime.IsLeapYear()

if(DateTime.IsLeapYear(Year))
{
    Console.WriteLine("The Year you have entered is a Leap Year {0}.", Year);
}
else
{
    Console.WriteLine("The Year you have entered is NOT a Leap Year {0}.", Year);
}