我该如何解决NullPointerException问题?

时间:2019-07-14 04:23:22

标签: java date nullpointerexception return-type

在这里,我收到一个NullPointerException问题,该问题似乎与班上的Date对象有关,但我无法弄清楚。
我的老师说,除了我为日期类返回错误的数据类型外,其他所有方法都有效,但是我知道我毕竟返回的是字符串,这是getDate()方法返回的

我已经尝试为getDate()方法本身添加代码,如
 "getMonth() + "/" + getDay() + "/" + getYear();

    //main employee class
public class Employee
{
    //2 attribute for employee
    private String name; 
    private Date dateHired;

    public boolean employeeType; //to check what type of employee, if 
    //false, then employee is salaried, otherwise hourly

    //setter methods
    public void setDateHired(int m, int d, int y)
    {
        Date dateHired = new Date(m,d,y);
    }

    public void setName(String s)
    {
        name = s;
    }

    public void setHoursWorked(int w)
    {

    }

    //getter methods
    protected String getDateHired()
    {
        return dateHired.getDate();
    }

应该没有错误,我检查了此代码数百次,一切似乎都很好!

2 个答案:

答案 0 :(得分:3)

public void setDateHired(int m, int d, int y)
{
    //dateHired is a local variable.. you're not modifying the class instance variable.
    Date dateHired = new Date(m,d,y);
}

应为:

public void setDateHired(int m, int d, int y)
{
    this.dateHired = new Date(m,d,y);
    //or: 
    //dateHired = new Date(m,d,y);
}

答案 1 :(得分:0)

在开始您的实际问题之前,您已经

private Date dateHired;

我建议您不要使用Date类。它总是设计不当,现在已经过时了。尽管它的名称也并不代表日期,但代表了全球有两个或三个不同日期的时刻。而是使用来自Java.time(现代Java日期和时间API)的LocalDate。使用底部的教程链接。

对于NullPointerException布兰登已经解释了以下几行的内容:

    Date dateHired = new Date(m,d,y);

使用LocalDate该行应为:

    dateHired = LocalDate.of(y, m, d);

new Date(m,d,y)中,您以错误的顺序获得了参数,您错误地对待了年和月,并且使用了已弃用了数十年的构造函数,从未如此。

  

我的老师说,除了我要退还   日期类的数据类型错误,但我知道我要返回一个字符串,   毕竟,这就是getDate()方法返回的内容

不推荐使用getDate方法,只要也不要使用该方法。它也没有给您完整的日期,您的老师是正确的,没有返回字符串,而是返回了int

  

我尝试将getDate()方法本身的代码放入其中,如下所示:   getMonth() + "/" + getDay() + "/" + getYear();

您会感到惊讶。但是,不要使用格式化程序将LocalDate格式化为字符串,而不会感到惊讶和困惑。

protected String getDateHired()
{
    DateTimeFormatter dateFormatter
            = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
    return dateHired.format(dateFormatter);
}

此方法的示例输出假设美国地区和雇用日期为2018年12月1日:

  

12/1/18

ofLocalizedDate为您提供了默认语言环境的格式化程序,因此,如果您的语言环境与美国不同,那么您可能会惊讶地发现字符串的格式比您引用的示例更符合您的期望。通常,人们将格式化程序声明为常量(类中的static final变量),但是我不确定您是否已经了解了这一点,因此在这种情况下,我还没有。

长话短说:正确使用过时的Date类比您想象的要困难得多,因为它的设计很差。不要为那一个而挣扎。现代LocalDate的使用自然而然地多了。它的编号年份和月份与人类相同(至少自公元1年起),并且其方法名称更清晰,仅提及其中许多优点。

教程链接Oracle tutorial: Date Time解释了如何使用java.time。