我有这段代码,当我运行脚本时,我传递了有效的参数,但我不断收到 NPE。 帮忙?
代码:
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;
}
我从上面代码的第 2 行得到 NullPointerException,并使用以下代码将 thisDate 作为 currentDate 变量传递。
Date thisDate = null;
try {
thisDate = (new SimpleDateFormat("MM/dd/yyyy")).parse(Calendar.getInstance().getTime().toString());
} catch (Exception e) {}
最佳答案
由于您已指出在第 2 行引发了 NullPointerException
,我们可以推断您正在为 currentDate
传入 null
> 论证。 currentDate.getTime()
是第 2 行中唯一可能导致 NullPointerException
的部分。
更新:
我刚刚编写了以下 Test.java
代码来真正了解您的问题是什么:
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();
}
}
}
当我运行它时,我得到:
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)
所以问题是你的 SimpleDateFormat.parse()
需要月/日/年格式,但是 Date
类的 toString()
> 方法给你一些不同的东西。
似乎您真正想要的只是当前日期。为什么要麻烦格式化呢?只需将其修剪到此即可完成:
Date thisDate = new Date(); // this gives you the current date
关于java - 我将如何修复以下代码的 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7134117/