I am trying to make a constructor that takes a string and constructs a date object. This is my solution so far but I am getting this error:
Constructor call must be the first statement in a constructor
private int m;
private int d;
private int y;
private String[] dateStrings;
public Date(int month, int day, int year) {
m = month;
d = day;
y = year;
}
public Date(String s) {
dateStrings = s.split("/");
this(Integer.parseInt(dateStrings[0]), Integer.parseInt(dateStrings[1]), Integer.parseInt(dateStrings[2]));
}
I realize I need this(...) before everything but how can I do that when I need to populate dateStrings first?
How can I avoid this error?
Note: to construct a date with a string it is in the format of “month/day/year”
this()needs to be called first.Instead move the assignment to a private method.
If you also need
dateStringspopulated, you can build it in this method too.Then call the method from both constructors. Make sure that the constructor accepting a String does not call
this()since the shared method takes care of assigning the values.You can also do everything in one line, but then you call
split()multiple times which is wasteful: