所以,我正在飞机上创建一系列座位,其特征是座位数,座位类型和乘客。
首先,我的代码将座位对象放在一个单独的类中:
public class Seat {
private int seatNumber;
private String passenger;
private String seatType;
public Seat(int seatNumber, String seatType, String passenger){
seatNumber=this.seatNumber;
seatType=this.seatType;
passenger=this.passenger;
}
public int getSeatNumber() {
return seatNumber;
}
public String getPassenger() {
return passenger;
}
public String getSeatType() {
return seatType;
}
在我的主要课程中,我有:
import javax.swing.*;
import java.awt.*;
import java.awt.List;
import java.util.*;
public class AirplaneReservation {
public static Seat []seatList= new Seat[12];
public void SeatList(){
for (int i=0; i<seatList.length; i++){
seatList[i]= new Seat(i, null, null);
}
Seat seat1 = new Seat(1, "First Class", "Collins");
seatList[0]=seat1;
Seat seat2 = new Seat(2, "First Class", "null");
seatList[1]=seat2;
Seat seat3 = new Seat(3, "First Class", "Faivre");
seatList[2]=seat3;
Seat seat4 = new Seat(4, "First Class", "Kinnard");
seatList[3]=seat4;;
Seat seat5 = new Seat(5, "Coach", "null");
seatList[4]=seat5;
Seat seat6 = new Seat(6, "Coach", "null");
seatList[5]=seat6;
Seat seat7 = new Seat(7, "Coach", "Morgans");
seatList[6]=seat7;
Seat seat8 = new Seat(8, "Coach", "Rohan");
seatList[7]=seat8;
Seat seat9 = new Seat(9, "Coach", "Shatrov");
seatList[8]=seat9;
Seat seat10 = new Seat(10, "Coach", "Sword");
seatList[9]=seat10;
Seat seat11 = new Seat(11, "Coach", "null");
seatList[10]=seat11;
Seat seat12 = new Seat(12, "Coach", "Tuckness");
seatList[11]=seat12;
}
public static void main (String [] args){
System.out.println("Seat\tPassenger");
System.out.println(seatList[0].getSeatNumber());
我发现很多人都遇到了不使用非null对象创建数组的问题,但是当我尝试使用我认为的代码块时,我仍然会得到一个空指针异常。
Exception in thread "main" java.lang.NullPointerException
at AirplaneReservation.main(AirplaneReservation.java:45)
如果不将这些对象设为null,我缺少什么?
答案 0 :(得分:0)
你的main()方法正在访问尚未填充的静态seatList字段(尚未调用SeatList())。
seatList应该是非静态的,并且可以通过getter方法访问,以强制该对象在使用之前完全初始化。
或使SeatList()静态并从静态初始值设定项中调用它以确保它被调用。
答案 1 :(得分:0)
这是一个空指针异常,因为你忘了调用函数将Seats添加到数组中。就像现在一样,你定义了一个Seats数组,但没有添加任何东西,所以默认情况下,一切都是null。
请记住在main方法中调用SeatList()。