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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7134117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:46:01  来源:igfitidea点击:

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

javaexceptionnullnullpointerexception

提问by Confiqure

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

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

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.

我从上面代码的第 2 行得到 NullPointerException,并使用以下代码将 thisDate 作为 currentDate 变量传递。

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

回答by Asaph

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

既然你已经表明,NullPointerException在第2行抛出,我们可以推断出你在传递nullcurrentDate参数。currentDate.getTime()是第 2 行中唯一可能导致NullPointerException.

Update:

更新:

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

我只是写了下面的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();
        }
    }
}

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 Dateclass's toString()method is giving you something different.

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

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

回答by rsp

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

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

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

A much easier way to obtain such a Dateis:

获得这样一个更简单的方法Date是:

thisDate = new Date();