Getter、Setter 和 NullPointerException

Getter, Setter & NullPointerException

提问人:Chin 提问时间:8/15/2021 更新时间:8/16/2021 访问量:707

问:

首先,我正在尝试为我本地初始化的数组分配值。数组的类类型存储在另一个类中,并且变量是私有的,因此我使用 getter 和 setter 来设置值。但它在房间显示“线程”main“java.lang.NullPointerException 中的异常。Test.main(Test.java:26)“,下面是我的 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();
        }
}

下面是我用来存储 Room 类型的类:

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;
    }
}

存储在我的房间.txt中的记录就像

RS11 Single Room 1 1
RD12 Double Room 1 0
java 数组 nullpointerexception 私有 getter-setter

评论


答:

1赞 Louis Wasserman 8/16/2021 #1

在开始调用其 setter 之前,您需要编写。room[I] = new Room();

0赞 tmarwen 8/16/2021 #2

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

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

  • nullfor 和 typesObjectString
  • 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) {
            // ...
        }
}