-4

I have a method that calculates age; calculateAge(User user):

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();
}

The prints are debugging lines, and as of now, this is what they print:

The DOB is 1-1-1988, but fields is [Ljava.lang.String;@6d41a4a instead of displaying the array of fields. As such, date, month, and year are printed as null and it can't Integer.parseInt(null), so it gives me a NumberFormatException: null.

cosmo
  • 751
  • 2
  • 14
  • 42
  • That's because fields is an address in memory that contains the formatted date, if you want to print the list you have to do it yourself. The reason the values are null is because you set them all to null in the 3 lines after you attempt to print fields. – Jacob H Jan 31 '17 at 14:27
  • 1
    `fields` is an array, not an `ArrayList`. And `date`, `month`, `year` are `null` because that's the value you assign them; you probably mean `date = fields[0];` etc. – Andy Turner Jan 31 '17 at 14:28

1 Answers1

3

That output is just Java's standard way of printing an array.

You just got your assignment the wrong way around, I think.

I guess it should be

date = fields[0]
months = fields[1]
year = fields[2]
eekboom
  • 5,551
  • 1
  • 30
  • 39