How would I go about fixing a NullPointerException of the following code?

被刻印的时光 ゝ 提交于 2019-12-22 12:53:20

问题


I have this code and when I run the script, I pass in valid parameters, but I keep on getting a NPE. Help?

Code:

private static Date getNearestDate(List<Date> dates, Date currentDate) {
    long minDiff = -1, currentTime = currentDate.getTime();
    Date minDate = null;
    if (!dates.isEmpty() && currentDate != null) {
        for (Date date : dates) {
            long diff = Math.abs(currentTime - date.getTime());
            if ((minDiff == -1) || (diff < minDiff)) {
                minDiff = diff;
                minDate = date;
            }
        }
    }
    return minDate;
}

I get the NullPointerException from line 2 of the code above and I use the following code to pass in thisDate as the currentDate variable.

Date thisDate = null;
try {
    thisDate = (new SimpleDateFormat("MM/dd/yyyy")).parse(Calendar.getInstance().getTime().toString());
} catch (Exception e) {}

回答1:


Since you've indicated that the NullPointerException is thrown on line 2, we can deduce that you're passing in null for the currentDate argument. currentDate.getTime() is the only part of line 2 that can cause a NullPointerException.

Update:

I just wrote the following Test.java code to really understand what your problem is:

import java.util.*;
import java.text.*;

class Test {
    public static void main(String[] args) {
        Date thisDate = null;
        try {
            thisDate = (new SimpleDateFormat("MM/dd/yyyy")).parse(Calendar.getInstance().getTime().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

When I run it, I get:

java.text.ParseException: Unparseable date: "Sat Aug 20 12:42:30 PDT 2011"
    at java.text.DateFormat.parse(DateFormat.java:337)
    at Test.main(Test.java:8)

So the problem is that your SimpleDateFormat.parse() expects the month/day/year format, but the Date class's toString() method is giving you something different.

It seems as though all you really want is the current date. Why bother formatting it? Just trim it down to this and be done with it:

Date thisDate = new Date(); // this gives you the current date



回答2:


What your line:

thisDate = (new SimpleDateFormat("MM/dd/yyyy")).parse(Calendar.getInstance().getTime().toString());

does is

  • create a new Calender object (initialised with the curren time),
  • get a Date() object from it,
  • convert that to string which will use a default format like "EEE MMM d HH:mm:ss z yyyy"
  • and try to parse the result as a date with the format "MM/dd/yyyy"
  • (which will fail to parse by design, resulting in a null)

If you fix all problems in this line, the end result will be a Date object containing the current time.

A much easier way to obtain such a Date is:

thisDate = new Date();


来源:https://stackoverflow.com/questions/7134117/how-would-i-go-about-fixing-a-nullpointerexception-of-the-following-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!