Мое задание состоит в том, чтобы завершить класс Date, показанный ниже. Класс Date инкапсулирует дату, сохраняя месяц, день и год в переменных частного экземпляра.Инкапсуляция, инициализация и постусловия данных Java?
public class Date
{
// declare your instance variables here
// postcondition: instance variables are initialized with any valid values
// you choose
public Date()
{
}
// postcondition: instance variables are initialized with the given values if they are valid
// the month instance variable should be between 1-12
// the day instance variable should be between 1-31
// if the parameters are not valid, the instance variables are given different values that are valid
public Date(int theMonth, int theDay, int theYear)
{
}
// postcondition: returns a String in the form month/day/year
public String toString()
{
}
}
код ниже, что я до сих пор. Честно говоря, я довольно смущен тем, что я должен делать, и у меня нет инструктора, чтобы спросить. Выходной сигнал «2/2/0»
EDIT UPDATE: Если я ввел год, который недействителен, например, 200, он не выводит сообщение об ошибке ... Мое намерение с помощью оператора if заключалось в сбое ошибок где год не 4 цифры. Это верно? Спасибо за любую помощь!
public class Date
{
// declare your instance variables here
private int myMonth;
private int myDay;
private int myYear;
// postcondition: instance variables are initialized with any valid values
// you choose
public Date()
{
myMonth = 11;
myDay = 11;
myYear = 2011;
}
// postcondition: instance variables are initialized with the given values if they are valid
// the month instance variable should be between 1-12
// the day instance variable should be between 1-31
// if the parameters are not valid, the instance variables are given different values that are valid
public Date(int theMonth, int theDay, int theYear)
{
if (theMonth >= 1 && theMonth <= 12) {
myMonth = theMonth;
}
else {
System.out.print("Month Value invalid; default to 1");
myMonth = 1;
}
if(theDay >= 1 && theDay <= 31) {
myDay = theDay;
}
else {
System.out.print("Day Value invalid; default to 1");
myDay = 1;
}
if(theYear < 4) {
System.out.print("Year Value invalid; default to 2000");
myYear = 2000;
}
else {
myYear = theYear;
}
}
// postcondition: returns a String in the form month/day/year
public String toString()
{
return myMonth + "/" + myDay + "/" + myYear;
}
public static void main(String [] args)
{
int theMonth, theDay, theYear;
theMonth = 2;
theDay = 2;
theYear = 200;
Date date = new Date(theMonth, theDay, theYear);
date.toString();
System.out.println(date);
}
}
В чем проблема? –
Вы никогда не устанавливаете значение 'myYear' в значение 'Year' в вашем конструкторе, если оно' = = 4'. Это должно быть 'if (theear <4) { System.out.print (« Значение года недействительно, по умолчанию 2000 »); myYear = 2000; } else { \t myYear = theYear; } ' –
Требования к послесловию не требуют проверки на год, поэтому вам не нужно проверять, составляет ли это четыре цифры или больше. – dasblinkenlight