我将如何修复以下代码的NullPointerException? [英] How would I go about fixing a NullPointerException of the following code?

查看:169
本文介绍了我将如何修复以下代码的NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码,当我运行脚本时,我传入了有效的参数,但我继续获得NPE。
帮助?

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

代码:

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变量传递的代码。

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) {}


推荐答案

由于你已经表明在第2行抛出了 NullPointerException ,我们可以推断你传入的是 null 对于 currentDate 参数。 currentDate.getTime()是第2行中唯一可能导致 NullPointerException 的部分。

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.

我刚才写了以下 Test.java 代码了解你的问题是什么:

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

当我运行它时,我get:

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)

所以问题是你的 SimpleDateFormat.parse()需要月/日/年格式,但是日期类的 toString()方法给你一些不同的东西。

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

这篇关于我将如何修复以下代码的NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆