Firstly, I am trying to assign the value for array I initialized locally. The class type of the array is stored inside another class and the variable is private so I am using getter and setter to set the value. But it showing “Exception in thread “main” java.lang.NullPointerException at room.Test.main(Test.java:26)”, below is my code for the 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(); } }
Below is the class I used to store the Room type:
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. The records stored inside my Room.txt is like
RS11 Single Room 1 1 RD12 Double Room 1 0
Advertisement
Answer
You need to write room[I] = new Room();
before you start calling its setters.