我制作了这个程序,它处理类和关系,当我运行它时,它给出了错误“线程中的异常”主“java.lang.NullPointerException”,我的IDE没有检测到编码中的任何错误,任何人都可以帮助我,这非常烦人。
import java.util.Vector;
class Flight {
private String id;
private String destination;
private Time depart;
private Time arrival;
private Vector passengerList;
public Flight(String a, String b, Time c, Time d) {
id = a;
destination = b;
depart = c;
arrival = d;
}
public void addPassenger(Passenger a) {
passengerList.add(a);
}
public void printInfo() {
System.out.println("Id " + id);
System.out.println("Destination " + destination);
System.out.println("Depart " + depart.getHour() + " " + depart.getMinute());
System.out.println("Arrival " + arrival.getHour() + " " + arrival.getMinute());
System.out.println("Number of passengers " + passengerList.size());
}
}
class Time {
private int hour;
private int minute;
public Time(int a, int b) {
hour = a;
minute = b;
}
public int getHour() {
return hour;
}
public int getMinute() {
return minute;
}
}
class Passenger {
private String name;
private int age;
public Passenger(String a, int b) {
name = a;
age = b;
}
}
class FlightTester {
public static void main(String[] args) {
Time dep = new Time(8, 10);
Time arr = new Time(9, 00);
Flight f = new Flight("PK-303", "Lahore", dep, arr);
Passenger psg1 = new Passenger("Umair", 30);
Passenger psg2 = new Passenger("Manzoor", 44);
f.addPassenger(psg1);
f.addPassenger(psg2);
f.printInfo();
}
}
答案 0 :(得分:0)
private Vector passengerList;
未初始化,可能是问题。
答案 1 :(得分:0)
Vector passengerList are not initialized.
致电
f.addPassenger(psg2);
你会得到NullPointException。
使用List会比vector
更好答案 2 :(得分:0)
private Vector passengerList;
你永远不会初始化它,所以当你的代码遇到任何引用passengerList的东西时,你会得到一个空指针异常。