如果我有生日和现在,我正试图让一个人的年龄。我所做的就是减去生日那一年的年份。当前年份是2014年。我的样品生日是1960年,但它返回0而不是53。
public class Person implements java.io.Serializable {
private static final long serialVersionUID = 7056942232246992667L;
String fname, mname, lname, houseNum, street, city, state, country;
ArrayList<String> schools = new ArrayList<String>();
int age, yr, mt, dy;
String zipCode, ssn, id;
static Calendar bday;
public Person(String fnamei, String mnamei, String lnamei, int yri, int mti, int dyi, String houseNumi, String streeti, String cityi, String statei, String zipi, String countryi, String idset) {
fname = fnamei; mname = mnamei; lname = lnamei; yr = yri; mt = mti; dy = dyi;
houseNum = houseNumi; street = streeti;
city = cityi; state = statei; zipCode = zipi; country = countryi;
id = idset; age = -1;
bday = new GregorianCalendar(yr, mt, dy);
GregorianCalendar currDate = new GregorianCalendar();
GregorianCalendar thisYearBDay = new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), mt, dy);
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
age = thisYear - yr;
if (currDate.before(thisYearBDay)) {
age--;
}
}
public int getAge() {
System.out.println(Calendar.getInstance().get(Calendar.YEAR)); //2014
System.out.println(bday.getInstance().get(Calendar.YEAR)); //1960
return age; //0? Should be 53/54
}
如何声明person对象:
Person sample = new Person("John", "Sample", "Doe", 1960, 5, 1, "100", "Test St.", "City", "US", "10000", "US", "10000001");
答案 0 :(得分:2)
你正在打电话
bday.getInstance().get(Calendar.YEAR) // 1960
getInstance()
是一个static
方法,它返回一个新的Calendar
对象。您可以在实例上调用static
方法,但出于这个原因,我们非常劝阻它。
你在新的实例上调用get(int)
,该实例初始化为今天,即。 2014年,而不是bday
引用的实例。
答案 1 :(得分:0)
我已经运行了您的示例并打印
2014
2014
53
“按预期”。
该行
System.out.println(bday.getInstance().get(Calendar.YEAR)); //1960
打印2014年,因为bday.getInstance()
创建了一个新的日历实例。要打印出生年份,请使用
System.out.println(bday.get(Calendar.YEAR)); //1960
另一个提议是声明除具体类之外的接口,例如:
List<String> schools = new ArrayList<String>();
Calendar currDate = new GregorianCalendar();