【发布时间】:2018-10-04 23:50:00
【问题描述】:
我想知道如何在另一个方法中使用布尔方法的结果。下面的代码包含两个方法,一个名为ValidateDay,另一个名为IsLeapYear。 IsLeapYear 确定用户输入的整数是否为闰年。 ValidateDay 根据用户输入的月份数检查用户输入的日期是否为有效日期。为了检查 2 月 29 日是否有效,我需要 ValidateDay 方法来了解 IsLeapYear 的结果是真还是假。但是,我不确定如何在ValidateDay 方法中引用IsLeapYear 的返回值。任何建议将不胜感激。
// Determines if day is valid
public Boolean ValidateDay()
{
IsLeapYear();
if(Month == 1 || Month == 3 || Month == 5 || Month == 7 || Month == 8 || Month == 10 || Month == 12)
{
if (Day >= 1 && Day <= 31)
{
return true;
}
else
{
return false;
}
}
else if (Month == 4 || Month == 6 || Month == 9 || Month == 11)
{
if (Day >= 1 && Day <= 30)
{
return true;
}
else
{
return false;
}
}
else if (Month == 2 && IsLeapYear(true))
{
if (Day >= 1 && Day <= 29)
{
return true;
}
else
{
return false;
}
}
else if (Month == 2 && IsLeapYear(false))
{
if (Day >= 1 && Day <= 28)
{
return true;
}
else
{
return false;
}
}
}
// Determine if year is a leap year
public Boolean IsLeapYear()
{
if ((Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0))
{
return true;
}
else
{
return false;
}
}
【问题讨论】:
-
Boolean isLeap = IsLeapYear();然后你可以在你的 if 语句中使用 isLeapelse if (Month == 2 && isLeap)和else if (Month == 2 && !isLeap) //! means NOT -
当然你可以在你的if语句中直接调用方法` else if (Month == 2 && IsLeapYear())`和` else if (Month == 2 && !IsLeapYear())`
-
还有一点
if (Month == 2 && ! isLeap)等于if (Month == 2 && isLeap == false)和if (Month == 2 && isLeap)等于if (Month == 2 && isLeap == true)
标签: c#