我将如何修复以下代码的 NullPointerException?
我有这段代码,当我运行脚本时,我传递了有效的参数,但我不断收到 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) {}
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) {}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您已指出在第 2 行引发了
NullPointerException
,因此我们可以推断您为currentDate
参数传递了null
。currentDate.getTime()
是第 2 行中唯一可能导致NullPointerException
的部分。更新:
我刚刚编写了以下
Test.java
代码来真正了解您的问题是什么:当我运行它时,我得到:
所以问题是您的
SimpleDateFormat.parse() 需要月/日/年格式,但是
Date
类的toString()
方法为您提供了不同的内容。似乎您真正想要的只是当前日期。为什么要麻烦格式化呢?只需将其修剪到此即可完成:
Since you've indicated that the
NullPointerException
is thrown on line 2, we can deduce that you're passing innull
for thecurrentDate
argument.currentDate.getTime()
is the only part of line 2 that can cause aNullPointerException
.Update:
I just wrote the following
Test.java
code to really understand what your problem is:When I run it, I get:
So the problem is that your
SimpleDateFormat.parse()
expects the month/day/year format, but theDate
class'stoString()
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:
你的行:
所做的是
null
)如果您解决了这一行中的所有问题,结束结果将是一个包含当前时间的
Date
对象。获取此类
Date
的更简单方法是:What your line:
does is
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: