I'm trying to set up a class that receives a date and if it's not a valid date sets it to 1/1/2000 (among other things it does)
So let's say this is how I check if it's validprivate static int numDaysInMonth(int month, boolean isLeapYear)
{
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if (isLeapYear)
{
return 29;
} else
{
return 28;
}
default:
return 0;
}
}
public static boolean isLeapYear(int year)
{
return (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0));
}
public static boolean isValidDate(int month, int day, int year)
{
return (month >= 1 && month <= 12) && (day >= 1 && day <= numDaysInMonth(month, isLeapYear(year))) && (year >= 0 && year <= maxYear);
}
And these are my constructors for the Date object
public Date(int day, int month, int year)
{
_day = day;
_month = month;
_year = year;
}
// Additional constructor
public Date(Date date)
{
_day = date._day
_month = date._month
_year = date._year
}
How do I "fuse" them so that every date I receive is checked to be valid and reset to 1/1/2000 if not?
I forgot to say it's java
>Terraria
good taste
>>57898064
>public Date(int day, int month, int year)
{
_day = day;
_month = month;
_year = year;
}
Who is teaching you java? The _attribute practice is usually used in languages that don't have private attributes to distinguish from public ones.
>>57898588
We aren't allowed to add our own private attributes, and only allowed to add private methods and finals
is that related to why they would do this
>>57898618
Nonsense.
Anyways, for your initial question, on each consutrctor, check if isValidDate(_day, _month, _year) == false, then assign _day = 1, _month = 1, _year = 2000.
Same thing for the 2nd constructor
>>57898653
Why nonsense? Is it stupid to teach that way?
Is it enough to just have the code for checking if a date is valid somewhere in the class, and then do the if isValidDate(_day, _month, _year) == false thing?
Like, do I need to declare any of those ints or booleans somewhere else or is it enough the way I wrote it here?
I'm just still not sure about totally basic stuff like this.
Also, if I need to check if a day I am setting in my set day methodpublic void setDay(int dayToSet)
{
_day = dayToSet;
}
But instead of changing to 1/1/2000 I don't change it at all (IE if a day changes from 31 to 32, nothing happens)
How do I use it here?
Guessing something likepublic void setDay(int dayToSet)
{
if isValidDate(dayToSet, _month, _year)
_day = dayToSet;
}
correct me if I'm wrong here.