0

Why do i keep getting NullPointerException error

public class Passenger { String firstName; String lastName; int expenses; public Passenger() { firstName = ""; } //Constructors public Passenger(String cabinFirstName, String cabinLastName, int pExpenses) { firstName = cabinFirstName; lastName = cabinLastName; expenses = pExpenses; } public void setFirstName(String cabinFirstName) { firstName = cabinFirstName; } public String getFirstName() { return firstName; } public void setLastName(String cabinLastName) { lastName = cabinLastName; } public String getLastName() { return lastName; } public void setExpenses(int pExpenses) { expenses = pExpenses; } public int getExpenses() { return expenses; } } public class Cabin { int cabinNumber; Passenger[] passenger = new Passenger[3]; public Cabin() { } public Cabin(int cabinNumber, Passenger[] passenger) { this.cabinNumber = cabinNumber; this.passenger = passenger; } public void setCabinNumber(int cNumber) { cabinNumber = cNumber; } public int getCabinNumber() { return cabinNumber; } } public class Main { public static Scanner scanner = new Scanner(System.in); public static Cabin[] myShip = new Cabin[12]; public static void main(String[] args) { for (int count = 0; count < 12; count++) { myShip[count] = new Cabin(); } myShip[0].passenger[0].setFirstName("a"); }

19th Apr 2022, 11:43 PM
FS00047
2 ответов
+ 2
because Cabin.passenger[] array is empty [null, null, null] and null.setFirstName("a") causes error //try myShip[0].passenger[0] = new Passenger(); myShip[0].passenger[0].setFirstName("a");
20th Apr 2022, 12:53 AM
zemiak
0
Thanks
20th Apr 2022, 12:13 PM
FS00047