我正在尝试创建一个构造函数,它接受一个字符串并构造一个日期对象。到目前为止,这是我的解决方案,但我收到此错误:
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]));
}
我意识到我需要 this(...)
在所有事情之前,但是当我需要首先填充 dateStrings 时我该怎么做?
我怎样才能避免这个错误?
注意:用字符串构造日期,格式为“月/日/年”
最佳答案
this()
需要首先调用。
而是将分配移至私有(private)方法。
private void assginValues (int month, int day, int year){
m = month;
d = day;
y = year;
}
如果您还需要填充dateStrings
,您也可以在此方法中构建它。
然后从两个构造函数中调用该方法。确保接受字符串的构造函数不会调用 this()
,因为共享方法负责分配值。
您也可以在一行中完成所有操作,但随后多次调用 split()
,这是浪费:
this(Integer.parseInt(s.split("/")[0]), Integer.parseInt(s.split("/")[1]), Integer.parseInt(s.split("/")[2]));
关于java - "Constructor call must be the first statement in a constructor"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14867536/