2017-01-31 29 views
-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

+0

這是因爲場是在內存中,如果你要打印你必須做你自己的列表,其中包含格式化的日期,地址。值爲空的原因是因爲您在嘗試打印字段後將它們全部設置爲null。 –

+1

'fields'是一個數組,而不是'ArrayList'。 'date','month','year'是'null',因爲這是你賦值的值;你可能是指'date = fields [0];'等等 –

回答

3

該輸出只是Java打印數組的標準方法。

我覺得你只是錯誤地分配了你的任務。

我想這應該是

date = fields[0] 
months = fields[1] 
year = fields[2]