我想知道如何在另一个方法中使用布尔方法的结果。下面的代码包含两个方法,一个名为ValidateDay
,另一个名为IsLeapYear
。 IsLeapYear
确定用户输入的整数是否为闰年。 ValidateDay
根据用户输入的月份检查用户输入的日期是否为有效日期。为了检查2月29日是否有效,我需要使用ValidateDay
方法来了解IsLeapYear
的结果是真还是假。但是,我不确定如何在IsLeapYear
方法中引用ValidateDay
的返回值。任何建议都会有很大的吸引力。
// 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;
}
}
在以下行中,将值true
传递给IsLeapYear()方法:
else if (Month == 2 && IsLeapYear(true))
但你的IsLeapYear()方法没有参数,我猜你打算在这里做的是评估IsLeapYear()的结果是否为真。只需将其更改为以下内容:
else if (Month == 2 && IsLeapYear() == true)
或者更简洁:
else if (Month == 2 && IsLeapYear())
检查值是否为false,只需使用!要评估的表达式之前的字符:
else if (Month == 2 && !IsLeapYear())
或者如果您愿意:
else if (Month == 2 && IsLeapYear() == false)
我想你可以尝试使用IsLeapYear()
和!IsLeapYear()
检查是否是LeapYear。
else if (Month == 2 && IsLeapYear())
{
if (Day >= 1 && Day <= 29)
{
return true;
}
else
{
return false;
}
}
else if (Month == 2 && !IsLeapYear())
{
if (Day >= 1 && Day <= 28)
{
return true;
}
else
{
return false;
}
}
在.net库中有一个DateTime.IsLeapYear方法我会用它来检查年份是否是LeapYear。
DateTime.IsLeapYear(year)
我觉得你有点过于复杂了。
试试这种方法:
public Boolean ValidateDay()
{
try
{
return Day >= 1 && Day <= DateTime.DaysInMonth(Year, Month);
}
catch (ArgumentOutOfRangeException)
{
return false;
}
}
public Boolean IsLeapYear()
{
try
{
return DateTime.IsLeapYear(Year);
}
catch (ArgumentOutOfRangeException)
{
return false;
}
}