简体   繁体   English

当用户输入无效数据时,避免NullPointerException

[英]Avoiding a NullPointerException when the user enters invalid data

How can I avoid a NullPointerException here if the user passes a null value for a date? 如果用户为日期传递空值,我该如何避免NullPointerException Ideally, I would use a simple if statement. 理想情况下,我会使用简单的if语句。

SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm");
String layupDate = dateFormatter.format(orderLayupDateSet.getLayupDate());  
String layupTime = timeFormatter.format(orderLayupDateSet.getLayupDate());
if(layupDate == null) {
}

You validate the date ( orderLayupDateSet.getLayupDate() ) in a liner (just creating a new date if null here but you can do as you please); 你在一个班轮中验证日期( orderLayupDateSet.getLayupDate() )(只是在这里创建一个新的日期,但你可以随意做);

(orderLayupDateSet.getLayupDate() == null) ? new Date() : orderLayupDateSet.getLayupDate()

You can also go the traditional 你也可以去传统

if (orderLayupDateSet.getLayupDate() == null) {
   orderLayupDateSet.setLayupDate(new Date());
}

Or you can do it the other way around with a utility, and calling the utility function to check for you - seeing that you return a String in your example above. 或者你可以用实用程序反过来做,并调用实用程序函数来检查你 - 看到你在上面的例子中返回一个字符串。 Like the below; 如下所示;

public class DateUtils {
    public static String formatDateTime(Date dateOrNull) {
        return (dateOrNull == null ? null : DateFormat.getDateTimeInstance().format(dateOrNull));
    }
}

Which in your code can be 在你的代码中可以是哪个

String layupDate = (orderLayupDateSet == null || orderLayupDateSet.getLayupDate() ? null : dateFormatter.format(orderLayupDateSet.getLayupDate()));  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM