-
I just dont get it
Hello every one!
Ok, im studying for a exam and having some problem with understandig one thing.
Code:
class Date
{
private static int[] daysInMonth =
new int[13] { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
private int year = 1, month = 1, day = 1;
public int Year { get { return year; } }
public int Month { get { return month; } }
public int Day { get { return day; } }
public Date(int y, int m, int d)
{
year = y; month = m; day = d;
Validate();
}
private bool IsLeapYear()
{ // ger sant om ºaret Äar ett skottºar
return ((Year % 4 == 0 && Year % 100 != 0) || Year % 400 == 0);
}
private int GetDaysInMonth()
{
if (Month == 2 && IsLeapYear()) { return 29; }
else return daysInMonth[Month];
}
private void Validate()
{
if (Year < 1) year = 1;
if (Month < 1 || Month > 12) month = 1;
if (Day < 1 || Day > GetDaysInMonth()) day = 1;
}
public void Set(int y, int m, int d)
{
year = y; month = m; day = d;
Validate();
}
public override string ToString()
{
return Year + "-" + Month + "-" + Day;
}
public static int operator -(Date date1, Date date2)
{
int count=0;
//Ok, here i want to use && instead of || cuz the thing i want to do is to
//loop this until date2 match date1 which it does when both conditions are
//fulfilled. In short, why doesent && work?
while (date2.month != date1.month || date2.day != date1.day)
{
count++;
date2.day++;
date2.Validate();
if (date2.day == 1)
date2.month++;
}
return count;
}
}
-
In short, the while loop executes only when the condition inside the parentheses evaluates to true.
TRUE || FALSE = TRUE;
TRUE && FALSE = FALSE;
FALSE || FALSE = FALSE;
so, if you put an && instead of an ||, it expects both expressions to be true and will stop evaluation even if a single one is false.
-
if you wanted to use &&, you could like this -
Code:
while (!(date2.month == date1.month && date2.day == date1.day))
-
Allright, now it works! Tyvm!
-
To elaborate a bit to help you understand WHY this is the case:
Two dates match if the month matches AND the day matches. That is, both must match in order for the entire date to match.
Two dates do not match if the month doesn't match OR the day doesn't match. That is, only one needs to mismatch for the whole date to mismatch.
In general, when you want to negate a complex expression, you just do 2 things:
1. You negate each term.
2. You switch all && to ||, and all || to &&, using parentheses if needed to keep the order of operations the same.
For example:
!( a && b && c ) = !a || !b || !c
!( a && (b || c) ) = !a || (!b && !c)
!( a && b || c ) = (!a || !b) && !c