简体   繁体   中英

Can someone please explain why I'm getting an error in this code

I'm making an throw IllegalArgumentException statement in my constructor class of my classs to check if the user's input's age is higher than the maxAge wanted. I'm using if statements to throw the IllegalArgumentException at the user if the age entered is higher than the maxAge . The error the IDE is giving me is an java.lang.NullPointerException .

I have tried to declare and assign the values outside the if statement like

int timePeriod = (Period.between(bday, LocalDate.now()).getYears()); 
int maxAge = 101;

to check if Im still getting the error. it seems like the problem is in the periods.between >> getYear statement.

Code:

    public Instructor(String fname, String lname, int ID, String road, String cty, String postalCode, LocalDate reg, LocalDate bDay) throws IllegalArgumentException 
    {   
        int timePeriod = (Period.between(bday, LocalDate.now()).getYears());
        int maxAge = 101; 
        System.out.print(timePeriod);
        //if (101 < (Period.between(bday, LocalDate.now()).getYears())) { 
        if (maxAge < timePeriod) { 

            throw new IllegalArgumentException("Please check the year entered, instructor cannot be over 100 years old.");
        } 
        else { 
            this.first = fname;
            this.last = lname;
            this.instructID = ID; 
            this.address = road;
            this.city = cty;
            this.postCode = postalCode;
            this.regDate = reg;
            this.bday = bDay;
        }   
    }

I believe your issue is that you are using the instance variable bday instead of the passed parameter bDay. bday has not been created yet and as such does not exist.

I suggest that you be extremely careful with close variable names like that. It will save you a lot of trouble as your projects get bigger and more complex.

Period.between(null, LocalDate.now());

Above code line will throw

java.lang.NullPointerException

Try passing non-null value in startDate and also add null checks in your code to avoid any such exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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