我将如何修复以下代码的 NullPointerException?

发布于 2024-11-30 11:53:59 字数 846 浏览 5 评论 0原文

我有这段代码,当我运行脚本时,我传递了有效的参数,但我不断收到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

世俗缘 2024-12-07 11:53:59

由于您已指出在第 2 行引发了 NullPointerException,因此我们可以推断您为 currentDate 参数传递了 nullcurrentDate.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

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
年华零落成诗 2024-12-07 11:53:59

你的行:

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

所做的是

  • 创建一个新的 Calender 对象(用当前时间初始化),
  • 从中获取一个 Date() 对象,
  • 将其转换为字符串,该字符串将使用默认格式,如“EEE MMM d HH:mm:ss z yyyy ”
  • 并尝试将结果解析为格式为“MM/dd/yyyy”的日期
  • (根据设计将无法解析,导致 null

如果您解决了这一行中的所有问题,结束结果将是一个包含当前时间的 Date 对象。

获取此类 Date 的更简单方法是:

thisDate = new Date();

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文