gpt4 book ai didi

Java 日期类 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 23:37:16 25 4
gpt4 key购买 nike

我正在尝试设置并返回字符串中的最早日期,并且我认为在设置日期时遗漏了一些内容,因为每当我尝试设置日期的值时,我都会收到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com