简体   繁体   中英

I'm wondering why I'm getting a java.lang.NullPointerException

I'm getting a java.lang.NullPointerException @ the start of the if here: if (name.equalsIgnoreCase(passengers[i].getName())) . This is when I enter a wrong name. There are a total of 500 passengers. Why? (This is only a small section of my code)

System.out.println("Booking Cancellation:");
System.out.println("--------------------");

name = null;
System.out.print("\nName of Passenger: ");
name = scan.nextLine();

for (int i = 0; i < 500; i++)
{

   if (name.equalsIgnoreCase(passengers[i].getName()))
   {
        passengers[i].setName(null);
        passengers[i].setAddress(null);
        passengers[i].setEmail(null);
        passengers[i].setOnFlight(0);
        passengers[i].setFlightBooked(false);
        flights[i].decreaseBookedSeats();
        bookedSeatsOverall = bookedSeatsOverall - 1;

        System.out.println("\nPassenger's details have been wiped from the system.");
        System.out.println("The booking has been cancelled.\n");

        break;
    }else if (i == 499)
    {
         System.out.println("\nNo bookings have been made under this name.\n");
         break;
    }

}

What is passengers ? Is it an array of length 500 ?

Is there a null passager in the array ?

Maybe the for loop can become

for (int i = 0; i < passengers.length; i++) {
  if (passengers[i] != null && passengers[i].getName() != null) {
    ...

Add this guard:

if (name != null &&
    passengers[i] != null && 
    name.equalsIgnoreCase(passengers[i].getName()))
{
    //...code here
    if (flights[i] != null){
       flights[i].decreaseBookedSeats();
    } else {
       // should not happen
    }
    // .. more code
 }

You have to make sure than name isn't null. Since nextLine may return null it has to be checked. The passengers[i] and flights[i] check shouldn't be necessary but if anywhere in your code you might set one of those cell in the array to null , then you have to always check if they are null or not.

You could also check for flights != null and passengers != null . But honestly, you should be able to find out easily by printing values to console or using a debugger. NullReference exceptions are usually easy to find and fix.

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