Getter、Setter & NullPointerException

Getter, Setter & NullPointerException

首先,我试图为我在本地初始化的数组赋值。数组的 class 类型存储在另一个 class 中并且变量是私有的,所以我使用 getter 和 setter 来设置值。但它在 room.Test.main(Test.java:26) 处显示“线程“main”java.lang.NullPointerException 中的异常”,下面是我的 test.java:

代码
public class Test {

    public static void main(String[] args) {
        Room[] room = new Room[72];
        Integer i = 0;
        try {
            File RoomTxt = new File("Room.txt");
            Scanner read = new Scanner(RoomTxt);
            while (read.hasNextLine()) {
                room[i].setRoomID(read.next());
                room[i].setRoomType(read.next() + " " + read.next());
                room[i].setFloor(read.nextInt());
                room[i].setRoomStatus(read.nextInt());
                read.nextLine();
                i++;
            }
            read.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
}

下面是class我用来存放房型的:

public class Room {

    private String roomID;
    private String roomType;
    private Integer floor;
    private Integer roomStatus;

    //Setter
    public void setRoomID(String roomID) {
        this.roomID = roomID;
    }

    public void setRoomType(String roomType) {
        this.roomType = roomType;
    }

    public void setFloor(Integer floor) {
        this.floor = floor;
    }

    public void setRoomStatus(Integer roomStatus) {
        this.roomStatus = roomStatus;
    }

    //Getter
    public String getRoomID() {
        return this.roomID;
    }

    public String getRoomType() {
        return this.roomType;
    }

    public Integer getFloor() {
        return this.floor;
    }

    public Integer getRoomStatus() {
        return this.roomStatus;
    }
}

PS。我的 Room.txt 中存储的记录就像

RS11 Single Room 1 1
RD12 Double Room 1 0

您需要在开始调用其设置器之前编写 room[I] = new Room();

初始化数组仅将数组引用分配给给定类型的新数组对象并分配数组内存space。

数组元素引用被初始化为默认元素类型值,即:

  • null 对于 ObjectString 类型
  • 0 数值
  • false boolean

因此所有 room[i] 元素都引用 null

你应该在调用任何方法之前分配元素值(包括 setter):

public class Test {

    public static void main(String[] args) {
        Room[] room = new Room[72];
        Integer i = 0;
        try {
            File RoomTxt = new File("Room.txt");
            Scanner read = new Scanner(RoomTxt);
            while (read.hasNextLine()) {
                room[I] = new Room();
                // set the field values
            }
            read.close();
        } catch (FileNotFoundException e) {
            // ...
        }
}