Java 日期类 NullPointerException

标签 java

我正在尝试设置并返回字符串中的最早日期,并且我认为在设置日期时遗漏了一些内容,因为每当我尝试设置日期的值时,我都会收到 nullreferenceexception。感谢您的帮助

private static Date createDate(String input)
{
    Date date = null;

    if (input == null)
        return null;

    // Split formatted input into separate values
    String tempDates[] = input.split(dateSep);

    // Store values as integers
    int[] dateValues = {0, 0, 0};
    dateValues[0] = Integer.parseInt(tempDates[0]);
    dateValues[1] = Integer.parseInt(tempDates[1]);
    dateValues[2] = Integer.parseInt(tempDates[2]);

    // Sort integers from lowest to highest
    Arrays.sort(dateValues);

    // Set return date
    date.setMonth(dateValues[0]);
    date.setDate(dateValues[1]);
    date.setYear(dateValues[2]);


    System.out.println(date);
    // Checking basic date restrictions
    if (date.getMonth() <= 0 || date.getMonth() > 12)
        throw new IllegalArgumentException("Month is not valid " + month);

    if (date.getDay() <= 0 || date.getDay() > 31)
        throw new IllegalArgumentException("Day is not valid " + day);

    if (date.getYear() <= 0)
        throw new IllegalArgumentException("Year is not valid " + year);


    return date;
}

}

最佳答案

您需要初始化Date对象。
将此行更改为 Date date = null;Date date = new Date();

通常你会得到NullPointerException

When you attempts to use null in a case where an object is required. These include:
1.Calling the instance method of a null object.
2.Accessing or modifying the field of a null object.
3.Taking the length of null as if it were an array.
4.Accessing or modifying the slots of null as if it were an array.
5.Throwing null as if it were a Throwable value.

关于Java 日期类 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18496244/

相关文章:

java - 编写 jBehave 示例步骤

java - 如果从 webview ~Android ~Java 打开,网页内的链接总是返回 "404 not found"错误

java - 嵌套事务用例中的外部事务未看到数据库中持久保存的更新(JPA、MySQL、Spring Framework 和 Hibernate)

java - 从最近的应用程序中删除应用程序后的 Jobscheduler

java - 使用接口(interface)的对象类继承

java - 从另一个类混淆调用方法(机器人类)

java - 在 Java 中实现不同方法的枚举

java - java中的泛型继承

java - 如何从没有 swing 组件初始化的线程将数据记录到 JTextArea(或 JTextPane)?

java - 通过 url 点击在注销表单中调用 ${_csrf.parameterName} 和 ${_csrf.token}