Reputation: 99
I would like to know how to use the result of a boolean method in another method. The code below contains two methods, one named ValidateDay
and another called IsLeapYear
. IsLeapYear
determines if a user entered integer is a leap year. ValidateDay
checks if the day a user enters is a valid day based on what number month the user entered. In order the check if Feb 29th is a valid day, I need the ValidateDay
method to know if the result of IsLeapYear
is true or false. However, I am not sure how to reference the return value of IsLeapYear
in the ValidateDay
method. Any advice would be greatly appretiated.
// 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;
}
}
Upvotes: 2
Views: 909
Reputation: 117027
I do feel like you're over-complicating this a bit.
Try this approach:
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;
}
}
Upvotes: 0
Reputation: 280
In the following line you pass the value true
to the IsLeapYear() method:
else if (Month == 2 && IsLeapYear(true))
but your IsLeapYear() method takes no parameters and I'm guessing that what you intend to do here is evaluate whether the result of IsLeapYear() is true. Simply change it to the following:
else if (Month == 2 && IsLeapYear() == true)
or more concisely:
else if (Month == 2 && IsLeapYear())
to check if the value is false, simply use a ! character before the expression to be evaluated:
else if (Month == 2 && !IsLeapYear())
or if you prefer:
else if (Month == 2 && IsLeapYear() == false)
Upvotes: 2
Reputation: 46219
I think you can try to use IsLeapYear()
and !IsLeapYear()
to check is or isn't 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;
}
}
There is a DateTime.IsLeapYear method in .net library I would use it to check the year is or isn't LeapYear.
DateTime.IsLeapYear(year)
Upvotes: 0