I have been asked to code a program (class) based on some certain instructions. I feel like I ALMOST got it down, but am doing something stupid. I cannot figure out how to add a hyphen into a symbolic constant so that when I type INSERT_HYPHEN it will insert a "-" into a accessors method. It says incompatible types>:( Also when I try to insert the local variable "fullDate" into the 'getFullDate' accessor method, and then put "fullDate = year + month + day" it indicates 'incompatible types! Perhaps it is because the accesor method is a string, and I am trying to add 'ints' inside it. I cannot find a way around it. Here is my code.
public class Date
{
public static final int INSERT_ZERO = 0;
public static final char INSET_HYPHEN = -; //ERROR incompatible types
// instance variables - replace the example below with your own
private int year;
private int month;
private int day;
/**
* Default constructor
*/
public Date()
{
setYear (2013);
setMonth (01);
setDay (01);
}
/**
*
*/
public Date (int whatIsYear, int whatIsMonth, int whatIsDay)
{
setYear (whatIsYear);
setMonth (whatIsMonth);
setDay (whatIsDay);
}
/**
*#return year
*/
public int getYear()
{
return year;
}
/**
*#return month
*/
public int getMonth()
{
return month;
}
/**
*#return day
*/
public int getDay()
{
return day;
}
/**
*#return
*/
public String getFullDate()
{
String fullDate;
if (whatIsMonth < 10); // the year, month, and day all give me incompatible types :(
{
fullDate = year + INSERT_HYPHEN + INSERT_ZERO + month + INSERT_HYPHEN + day;
}
if (whatIsDay < 10);
{
fullDate = year + INSERT_HYPHEN + month + INSERT_HYPHEN + INSERT_ZERO + day;
}
else
{
fullDate = year + INSERT_HYPHEN + month + INSERT_HYPHEN + day;
}
return year + month + day;
}
/**
*
*/
public void setYear (int whatIsYear)
{
if ((whatIsYear >= 1990) && (whatIsYear <= 2013))
{
year = whatIsYear;
}
else
{
year = 2013;
}
}
/**
*
*/
public void setMonth (int whatIsMonth)
{
if ((whatIsMonth >= 1) && (whatIsMonth <= 12))
{
month = whatIsMonth;
}
else
{
month = 01;
}
}
/**
*
*/
public void setDay (int whatIsDay)
{
if ((whatIsDay >= 1) && (whatIsDay <= 31))
{
day = whatIsDay;
}
else
{
day = 01;
}
}
}
Just for some more background. This class that I am constructing has three fields, to hold year, month and day. Years can be between 1900 and the current year, inclusive. Months can be between 1 and 12
inclusive. Days can be between 1 and 31 inclusive. I have to use symbolic constants instead of “magic” numbers in the code, e.g. public static final int FIRST_MONTH = 1;
The default constructor sets year to the current year, month to the first month and day to the first day. The non-default constructor tests each parameter. If the year parameter is outside the acceptable range, it sets the field to the current year. If the month parameter is outside the acceptable range, it sets the field to the first month. If the day parameter is outside the acceptable range, it sets the field to the first day.
Each field has an accessor method and a mutator method. All three mutator methods check their parameter for validity, and if not valid set the corresponding field in the same way as the nondefault
constructor.
This is the part that I am having trouble with. I have to include a method called "public String getFullDate() which returns a string with the date in this format: YYYY-MM-DD e.g. 2012-01-01. Month and day with a single digit are padded with a leading zero."
Any help whatsoever would be appreciated, even if just an idea :) Thanks.
You should use single quotes:
public static final char INSET_HYPHEN = '-';
fullDate = String.format("%d-%02d-%02d", year, month, day);
char type only holds data enclosed in single quotation mark. If you want to use double quotation mark then your datatype should be string
apart from the syntax error of declaring an charcter incorrectly you are trying to access local variables declared in your constructor in a getFullDate() method
public Date (int whatIsYear, int whatIsMonth, int whatIsDay)
public String getFullDate()
{
String fullDate;
if (whatIsMonth < 10); // the year, month, and day all give me incompatible
//rest of the code
}
whatIsMonth , whatIsDay are local variables defined in your constructor, you can't use these variables outside the constructor.
your getFullDate() method should rather be using your instance variables year, month and 'day'. note that int whatIsYear, int whatIsMonth, int whatIsDay are only constructor arguments and are confined to your constructor only. you can't access them outside the constructor.
you can not add a string literal, and if you want to use something as above :
then try this
public static final CHARACTER INSET_HYPHEN = new CHARACTER('-');
or
public static final char INSET_HYPHEN = '-';
Use public static final char INSET_HYPHEN = '-'; instead of public static final char INSET_HYPHEN = -; - Characters should always be defined between apostrophes.
It doesn't make sense to name a constant "INSERT_HYPHEN". The idea of constants is to make it easier to later change it's value wherever it is found in the code, so the name of the constant should represent the "roll" of it's value, for example: "SEPARATOR" or "DATE_FORMAT_SEPERATOR".
Anyway, if any values should be constants, it is the default values of year, month and day.
Your default constructor pretty much duplicates the code of the constructor that takes year, month and day, in which case it is often best to call the second from the default using this(default arguments).
The logic of getFullDate() is wrong, and it is anyway much better to let String.format do the dirty work for you. Also, getFullDate() returns year + month + day, which is an integer, instead of returning fullDate.
You might find it confusing, but it is better to name the arguments of setters and constructors the same way as the target field, instead of making up a new name. In order to avoid the ambiguity between the two, use this.[FIELD_NAME] to refer to the instance's field.
This code should work:
public class Date {
private static final int DEFAULT_YEAR = 2013;
private static final int DEFAULT_MONTH = 1;
private static final int DEFAULT_DAY = 1;
private static final char SEPARATOR = '-';
private int year;
private int month;
private int day;
/**
* Default constructor
*/
public Date() {
this(DEFAULT_YEAR, DEFAULT_MONTH, DEFAULT_DAY);
}
/**
*
*/
public Date (int year, int month, int day) {
setYear(year);
setMonth(month);
setDay(day);
}
/**
*#return year
*/
public int getYear() {
return year;
}
/**
*#return month
*/
public int getMonth() {
return month;
}
/**
*#return day
*/
public int getDay() {
return day;
}
/**
*#return
*/
public String getFullDate() {
return String.format("%d%c%02d%c%02d", year, SEPARATOR, month, SEPARATOR, day);
}
/**
*
*/
public void setYear (int year)
{
this.year = ((year >= 1990) && (year <= DEFAULT_YEAR)) ? year : DEFAULT_YEAR;
}
/**
*
*/
public void setMonth (int month)
{
this.month = ((month >= 1) && (month <= 12)) ? month : DEFAULT_MONTH;
}
/**
*
*/
public void setDay (int day)
{
this.day = ((day >= 1) && (day <= 31)) ? day : DEFAULT_DAY;
}
}
Related
I was doing one of my projects and couldn't really work my set method. And my set constructor was not working. I am new in class and need help. it will be a great help if you guys help me thank you.
My Class is:
public class date {
private int day;
private int month;
private int year;
public date ()
{
day = 1;
month = 1;
year = 1900;
}
I set up the constructor hear this is how it goes:
// set constructor
public date (int a,int b,int c) //(day,month,year)
{
if (a <1)
{
day = 1;
a = day;
}
if (b<1)
{
month = 1;
b = month;
}
if (c<1900)
{
year = 1900;
c = year;
}
else
{
a = day;
b = month;
c = year;
}
}
this is where I started to set the veribals as an mutators
// set date
public void setDay (int a)
{
if (a <1)
{
day = 1;
a = day;
}
else
a = day;
}
// set month
public void setMonth (int a)
{
if (a <1)
{
month = 1;
a = month;
}
else
a = month;
}
// set year
public void setYear (int a)
{
if (a <1990)
{
year = 1990;
a = year;
}
else
a = year;
}
And this is where I started to write my accessories
//Accsessors
public int getDay ()
{
return day;
}
public int getMonth ()
{
return month;
}
public int getYear ()
{
return year;
}
}
my main class is:
public class checkDate {
public static void main (String [] args)
{
date year1 = new date();
date year2 = new date (21,3,1995);
year1.setDay(13);
year1.setMonth(12);
year1.setYear(2010);
System.out.println(year1.getDay());
System.out.println(year1.getYear());
System.out.println(year2.getYear());
}
}
Output is:
1
1900
0
I tried checking everything I even tried to change the value but nothing works only thing I get is 1 and 1900
Many of the assignment statements are backwards. The expression on the right of the equals is assigned to the variable on the left. Here is what they should look like instead:
public date(int a, int b, int c) {
if (a < 1)
a = 1;
if (b < 1)
b = 1;
if (c < 1900)
c = 1900;
day = a;
month = b;
year = c;
}
The setters have a similar problem. Don't assign to the parameter, assign to the instance variable.
public void setDay(int a) {
if (a < 1)
a = 1;
day = a;
}
public void setMonth(int a) {
if (a < 1)
a = 1;
month = a;
}
public void setYear(int a) {
if (a < 1990)
a = 1990;
year = a;
}
Note: For more readable code, use better parameter names. Instead of reusing a, perhaps you should use d, m or y depending on the setter. Also, typical Java naming conventions always capitalize the first letter of class names, so you should use Date instead of date.
You're only setting the day and month when they are less than 1, and the year when it's less than 1990. You should probably flip those "<" into ">".
The problem lies in your variable assignments.
You could condense your code like this, by using the ternary operator:
public class Date{
private int day;
private int month;
private int year;
public Date(int d, int m, int y){
day = d<1 ? 1 : d;
month = m<1||m>12 ? 1 : m;
year = y<1900 ? 1990 : y;
}
public int getDay(){
return day;
}
...
public void setDay(int d){
day = d<1 ? 1 : d;
}
...
}
This question already has answers here:
How to return multiple objects from a Java method?
(25 answers)
Return multiple values from a Java method: why no n-tuple objects?
(7 answers)
Closed 6 years ago.
I have a method to find the day after but I don't know how to return all 3 values day,month,year.Please help me. Any help is appreciated.Thanks in advance.
public int dayInMonth(int day,int month,int year){
//....
return day;
}
public int theDayAfter(int day, int month, int year) {
day++;
int max=dayInMonth(day,month,year);
if(day>max)
{
month++;
if(month>12)
{
year++;
month=1;
day=1;
}
}
return ;
}
It is a valid doubt and a year ago even I was facing such a similar doubt.
I found out that the best way to return such values from a method is to return it in type of an Object. In this example, if I were to return day, month and year then I would create a class as follows:
public class DateOfYear{
public int day;
public String month;
public int year;
public DateOfYear(int day, String month, int year){
this.day = day;
this.month = month;
this.year = year;
}
}
Now I will use this class DateofYear instantiate it and send values as an object. So, if you would like to get the Day of the month, the function will be as follows:
public DateOfYear dayInMonth(int day,int month,int year){
//....
return new DateOfYear(day,month,year);
}
and the calling function can simply display the current day as follows:
System.out.println("Day: "+dayInMonth(day,month,year).day);
Similarly for the method theDayAfter simply change the return type and return the object of type DateOfYear.
public DateOfYear theDayAfter(int day, int month, int year) {
day++;
int max=dayInMonth(day,month,year);
if(day>max)
{
month++;
if(month>12)
{
year++;
month=1;
day=1;
}
}
return new DateOfYear(day, month, year);
}
The method calling theDayAfter() can display the next day as follows:
System.out.println("Next Day: "+theDayAfter(day,month,year).day);
System.out.println("Month: "+theDayAfter(day,month,year).month);
System.out.println("Year: "+theDayAfter(day,month,year).year);
I have a class Appointment with fields:
int day
int month
int year
String desc
This stores the description of the appointment along with the date.
Super class Appointment:
public class Appointment {
int dayNum;
int monthNum;
int yearNum;
String desc;
public Appointment(String des, int day) {
//Monthly Appointments (Check day)
desc = des;
dayNum = day;
}
public Appointment(String des, int day, int month){
//Yearly Appointments (Check day AND month)
desc = des;
dayNum = day;
monthNum = month;
}
public Appointment(String des, int day, int month, int year){
//One Time (Check All)
desc = des;
dayNum = day;
monthNum = month;
yearNum = year;
}
}
Here are my 3 sub classes:
A one time Appointment: Onetime
public class OneTime extends Appointment{
public OneTime(String des, int day, int month, int year){
super(des, day, month, year);
}
public String getDesc(){
return desc;
}
}
Once a month Appointments: Monthly
public class Monthly extends Appointment{
public Monthly(String des, int monum){
super(des, monum);
}
public String getDesc(){
return desc;
}
}
Once a year Appointments Yearly
public class Yearly extends Appointment{
public Yearly(String des, int day, int month){
super(des, day, month);
}
public String getDesc(){
return desc;
}
}
Problem: I am asked to add a handful of various Appointment objects to an ArrayList (which I know). However, I must write a method occursOn(int day, int month, int year) that returns all appointments on that day. The part I am not sure about is writing the occursOn() method. Say I had an Appointment for 11/22/2018 , how would I compare a Monthly object to the day parameter / Yearly compared to the month and day parameters / OneTime compared to all parameters?
Textbook question: " Implement a superclass Appointment and subclasses Onetime, Daily, and Monthly. An appointment has a description (for example, "see the dentist") and a date. Write a method occursOn(int year, int month, int day) that checks whether the appointment occurs on that date. For example, for a monthly appointment, you must check whether the day of the month matches. Then fill an array of Appointment objects with a mixture of appointments. Have the user enter a date and print out all appointments that occur on that date. "
Note: This is not my homework. I just have a unit test on this in 2 hours and am stuck.
First of all, you may want to declare Appointment abstract, so that sublcasses have to implement some methods :
public abstract class Appointment {
int dayNum;
int monthNum;
int yearNum;
String desc;
public Appointment(String des, int day){desc = des; dayNum = day;} //Monthly Appointments (Check day)
public Appointment(String des, int day, int month){desc = des; dayNum = day; monthNum = month;} //Yearly Appointments (Check day AND month)
public Appointment(String des, int day, int month, int year){desc = des; dayNum = day; monthNum = month; yearNum = year;} //One Time (Check All)
abstract boolean occursOn(int day, int month, int year);
abstract String getDesc();
}
Then, the implementation of occursOn in your classes could be :
Monthly
boolean occursOn(int day, int month, int year){
return (this.day == day);
}
Yearly
boolean occursOn(int day, int month, int year){
return (this.day == day) && (this.month == month);
}
OneTime
boolean occursOn(int day, int month, int year){
return (this.day == day) && (this.month == month) && (this.year == year);
}
Finally, assuming that appointments is a List you populated with various instances of the subclasses, have a general method (maybe in your main class), which will return the list of all corresponding Appointment objects :
public List<Appointment> occursOn(int year, int month, int day){
List<Appointment> result = new ArrayList<Appointment>();
for(Appointment appointment : appointments){
if(appointment.occursOn(year, month, day))
result.add(appointment);
}
return result;
}
OccursOn()
Should be an abstract method in the superclass (Appointment).
Each one of your sub class will have to implements it accordingly.
Onetime - check day, month, and year.
Monthly - check day only.
Yearly - check day and month.
One way to go would be a map that uses a "date" key with optional values, e.g. like this:
class DateKey {
int day; //always needed
Integer month; //null in case of monthlies
Integer year; //null in case of monthlies and yearlies
//override equals() and hashCode()
}
Use the date key for a map:
//handling this would be easier with Google Guava's Multimap, if you may use it
Map<DateKey, List<Appointment>> appointments = ...;
Then you use a 3-step lookup:
List<Appointment> onetimes = appointments.get(new DateKey( day, month, year) );
List<Appointment> yearlies= appointments.get(new DateKey( day, month, null) );
List<Appointment> monthlies = appointments.get(new DateKey( day, null, null) );
And finally combine the 3 lists.
Finally, the DateKey could also be part of the Appointment class which would make the mapping even more consistent. I'd probably use a slightly different name then (think of one) since it's not only a map key anymore.
You can add a method to your Appointment class that determines if the Appointment is on on a given date like this.
public class Appointment {
int dayNum;
int monthNum;
int yearNum;
String desc;
public Appointment(String des, int day){desc = des; dayNum = day;} //Monthly Appointments (Check day)
public Appointment(String des, int day, int month){desc = des; dayNum = day; monthNum = month;} //Yearly Appointments (Check day AND month)
public Appointment(String des, int day, int month, int year){desc = des; dayNum = day; monthNum = month; yearNum = year;} //One Time (Check All)
boolean occuresOn(int day, int month, int year){
if( (this.dayNum == day) && (this.monthNum == month) && (this.yearNum == year))
return true;
return false;
}
}
And override this functionality in sub classes.
public class Monthly extends Appointment{
public Monthly(String des, int monum){
super(des, monum);
}
public String getDesc(){
return desc;
}
boolean occuresOn(int day, int month, int year){
if( (this.dayNum == day) )
return true;
return false;
}
}
public class Yearly extends Appointment{
public Yearly(String des, int day, int month){
super(des, day, month);
}
public String getDesc(){
return desc;
}
boolean occuresOn(int day, int month, int year){
if( (this.dayNum == day) && (this.monthNum == month))
return true;
return false;
}
}
now you can iterate over your appointments and find those that are on a date:
List<Appointment> aps = new ArrayList<>(); //initialize this
for (Appointment ap : aps){
if(ap.occuresOn(2, 3, 2016))
....
}
public class hw16 {
public static void main(String[] args) {
MonthlyRecord MonthRecord = new MonthlyRecord("January", 31);
MonthRecord.Transaction(5, 600);
}
}
public class MonthlyRecord {
private String month;
private int day;
private double[] moneyDaily = new double[day];
public MonthlyRecord() {
this.month = "January";
this.day = 0;
this.moneyDaily[1] = 0;
}
public MonthlyRecord(String name, int day) {
System.out.println("Hello");
this.setMonthlyRecord(name);
this.setDays(day);
}
public void setDays(int temp) {
this.day = temp;
}
public void setMonthlyRecord(String temp) {
this.month = temp;
}
public int setDays() {
return this.day;
}
public String getMonthlyRecord() {
return this.month;
}
public void Transaction(int daynum, int amount) {
System.out.println("You've made $" + amount + " on the " + daynum + "th day");
System.out.println(moneyDaily[daynum]);
}
}
I'm getting an error:
Hello You've made $600 on the 5th day Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 5 at
hwk16jzuramski1.MonthlyRecord.Transaction(MonthlyRecord.java:40) at
hwk16jzuramski1.Hwk16jzuramski1.main(Hwk16jzuramski1.java:11) Java
Result: 1
SO it say's my array is out of bounds which I don't understand? If I'm setting day to the length of my array why is it saying its out of bounds at int 5 when the array length should be 31?
What I think is happening is that at the top of your class your are instantiating the array monthDaily[] outside of the constructor. Since the int variable day only gets initialized in the constructors you should also instantiate the monthDaily[] variable in the constructor. Hence the beginning part of your code would look like:
public class MonthlyRecord {
private String month;
private int day;
private double[] moneyDaily;
public MonthlyRecord() {
this.month = "January";
this.day = 0;
this.moneyDaily = new double[1]; //variable is instantiated to have one slot as default
}
public MonthlyRecord(String name, int day) {
System.out.println("Hello");
this.setMonthlyRecord(name);
this.setDays(day);
moneyDaily = new double[days]; //array gets instantiated with number of slots equal to the value of the day variable
}
You need to set the size of the array upon calling the constructor:
public MonthlyRecord(String name, int day) {
moneyDaily = new double[day];
System.out.println("Hello");
this.setMonthlyRecord(name);
this.setDays(day);
}
Otherwise, your array moneyDaily will have the size of what day was originally, which is 0.
I have the next code, and this code has to validate a date, but there are some requirements that i have to follow:
First of all i have to create a class named MyDate, this class contains three attributes: day, month and year. I have to initialize these attributes with a constructor without parameters.
Then I have to define three methods: setDay(),setMonth() and setYear(), inside this methods i have to validate if a date is correct. In the main method() i have to invoke the set methods, but the problem is that i don´t know how to initialize the attributes with the constructor, while at the same time i am already initializing them in the main when i call the set methods
class MyDate{
final int JANUARY = 1;
final int FEBRUARY = 2;
final int MARCH = 3;
final int APRIL = 4;
final int MAY = 5;
final int JUNE = 6;
final int JULY = 7;
final int AUGUST = 8;
final int SEPTEMBER = 9;
final int OCTOBER = 10;
final int NOVEMBER = 11;
final int DECEMBER = 12;
private int day;
private int month;
private int year;
public MyDate(){
//here is the problem;
}
public int getDay()
{
return day;
}
public int getMonth()
{
return month;
}
public int getYear()
{
return year;
}
public boolean setDay(int day)
{
//is not finished
}
public boolean setMonth(int month)
{
//is not finished
}
public boolean setYear(int year)
{
//is not finished
}
}
public class E{
public static void main(String[] args){
MyDate date = new MyDate();
date.setDay(31);
date.setMonth(11);
date.setYear(2014);
System.out.println("DAY: "+date.getDay());
System.out.println("MONTH: "+date.getMonth());
System.out.println("YEAR: "+date.getYear());
}
}
I'm not sure if I totally understood what you want, particularity the part where you want to set the variables in a constructor without parameters. How about the following solution? You can create a default Constructor as well and call this(1, 1, 2015).
class MyDate {
public MyDate() {
this(1, 1, 2015);
}
public MyDate(int day, int month, int year){
setDay(day);
setMonth(month);
setYear(year);
}
public void setDay(int day) {
if (isValid(day, month, year))
this.day = day;
else
throw new RuntimeException("Day is not valid.");
}
private boolean isValid(int day, int month, int year) {
// Your validation logic should go here.
}
Similar to setDay you can define setMonth and setYear for setting day and month. Your validation logic should go into isValid.
Your design is poor from 2 points:
First problem:
Having separate setters allows the state (fields) to be invalid until all setters are called. This is bad. Also bad is if you change from 31 Mar to 28 Feb (both valid), but happen to change the month first, the date is temporarily invalid (31 Feb). Also bad.
The 3 fields should be set atomically (in one action) using one method that sets all 3.
Second problem:
You have setters! Make your class immutable (no setters, final fields). If you need to "change" a date, make a new one. String works like this - it will work for you too.
class MyDate{
final int JANUARY = 1;
final int FEBRUARY = 2;
final int MARCH = 3;
final int APRIL = 4;
final int MAY = 5;
final int JUNE = 6;
final int JULY = 7;
final int AUGUST = 8;
final int SEPTEMBER = 9;
final int OCTOBER = 10;
final int NOVEMBER = 11;
final int DECEMBER = 12;
private final int day;
private final int month;
private final int year;
public MyDate(int d, int m, int y) {
day = d;
month = m;
year = y;
}
public int getDay() {
return day;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
public boolean isValid() {
// put your impl here
}
}
public class E {
public static void main(String[] args){
MyDate date = new MyDate(31, 11, 2014);
System.out.println("DAY: " + date.getDay());
System.out.println("MONTH: " + date.getMonth());
System.out.println("YEAR: " + date.getYear());
}
}
If you want, you could add a line to the constructor to allow only valid dates:
if (!isValid())
throw new IllegalArgumentException();
I have to initialize these attributes with a constructor without parameters.
Unless you are required to provide an explicit starting value for these parameters, you're pretty much done with that step already. Java will set an initial value for your fields, so each of those ints are set to 0 by the time you type new MyDate().
If you are required to start at specific values, then put them directly into the body of the no-arg constructor.
public MyDate() {
this.year = 2015;
this.month = 1;
this.day = 7;
}
I don't know how to initialize the attributes with the constructor, while at the same time I am already initializing them in main when I call the set methods
This is how POJOs work, in a sense. You create some class that does have a decent number of fields, but you only set the ones you care about.
Because you can rely on the initial value guarantee provided by the Java Language Specification, you don't have to worry about initializing those values unless you require them to be an explicit initial value besides zero.
Here is an Example on initializing Variable using Constructor:
Checked if it is FEBRUARY and Change Day Limit to 28, If False define max day to 30~31
class MyDate{
private int day;
private int month;
private int year;
public MyDate(){
this(1,1,2014);
}
public MyDate(int day, int month, int year){
this.day = day;
this.month = month;
this.year = year;
}
public int getDay()
{
return day;
}
public int getMonth()
{
return month;
}
public int getYear()
{
return year;
}
public boolean setDay(int day)
{
if(month == 2){
if(day>0 && day <=28){
this.day = day;
return true;
}else{
return false;
}
}else{
if( month % 2 != 0){
if(day>0 && day <=31){
this.day = day;
return true;
}else{
return false;
}
}else{
if(day>0 && day <=30){
this.day = day;
return true;
}else{
return false;
}
}
}
}
public boolean setMonth(int month)
{
if(month>0 && month <=12){
this.month = month;
return true;
}else{
return false;
}
}
public boolean setYear(int year)
{
// Not Required
if(year>1993 && year <=2018){
this.year = year;
return true;
}else{
return false;
}
}
}
public class E{
public static void main(String[] args){
MyDate date = new MyDate();
date.setDay(31);
date.setMonth(11);
date.setYear(2014);
System.out.println("DAY: "+date.getDay());
System.out.println("MONTH: "+date.getMonth());
System.out.println("YEAR: "+date.getYear());
}
}
If you can't pass any parameters to the constructor then all you can really do is initialize the object's variables to zero. The object won't contain a valid date, however, until you call your set methods which contains the validation code. The main reason for doing this is to avoid "variable might not have initialized" errors.
public MyDate(){
year = 0;
month = 0;
day = 0;
}
Just make sure that the validation code for setDay checks that the month and year don't equal zero still, otherwise it will be impossible to determine if the day value is valid.