-4
我有一種計算年齡的方法; calculateAge(User user)
:String.split(「 - 」)不起作用
public int calculateAge(User user) {
String date = null, month = null, year = null;
String[] fields;
String DOB = user.getDOB();
System.out.println(DOB);
fields = DOB.split("-");
System.out.println(fields);
fields[0] = date;
fields[1] = month;
fields[2] = year;
System.out.println(date);
System.out.println(month);
System.out.println(year);
LocalDate birthDate = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(date));
LocalDate now = LocalDate.now();
Period age = Period.between(birthDate, now);
return age.getYears();
}
打印件調試線,以及截至目前,這是他們打印的內容:
的出生日期是1988年1月1日,但場是[Ljava.lang。字符串; @ 6d41a4a而不是顯示字段數組。因此,日期,月份和年份打印爲null並且它不能Integer.parseInt(null)
,所以它給我一個NumberFormatException: null
。
這是因爲場是在內存中,如果你要打印你必須做你自己的列表,其中包含格式化的日期,地址。值爲空的原因是因爲您在嘗試打印字段後將它們全部設置爲null。 –
'fields'是一個數組,而不是'ArrayList'。 'date','month','year'是'null',因爲這是你賦值的值;你可能是指'date = fields [0];'等等 –